Replace only one line in text file

Question:

Here is the text file I want to modify:

The two values I want to modify are on line 2 and 5 (Index 1 and 4), which are the current year and the current month.

So I did this PowerShell script:

But obviously, this line

will replace all the “6” in my file with the current month (which is 7 at the time I’m writing these lines), but I only want the 5th line to be replaced, not the 2nd.

Answer:

You don’t need replace old value with new value, you can instead select the appropriate line by index and just replace the values:

Be aware that the Set-Content cmdlet may change the file encoding.

Source:

Replace only one line in text file by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply