I want to write a snippet of PowerShell code that would replace all occurences of string in file, but just if that string is at the end of the line.
I would like to replace string "ABC:A" with "Z", but I want to make sure that string "ABC:ACN" would not be part of the replacement.
$qFileName = "c:\project\myFile.txt";
To replace just end of the line, I attempted to change my code to:
But that did not help – no replacement is done at all.
The good thing for you is -replace uses regular expressions. So, this is a pretty simple matter..
You just need to modify this line, and it should work..
$qFile -replace ",ABC:A`n", "Z`n" | out-File $qFileName -Encoding OEM # Replace the above line with this: $qFile -replace ",ABC:A$", "Z" | out-File $qFileName -Encoding OEM
Because you don't necessarily know the line ending, the $ represents the end of the line no matter what the line endings are..
Thank you very much for your answer! I spend hours trying to figure this out.
You must be logged in to reply to this topic.