PowerShell - replace string in file, but just at the end of the line


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.
So my file:


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.
My code:

$qFileName = “c:\project\myFile.txt”;
$qFile = @(Get-Content -Path $qFileName);
$qFile -replace “,ABC:A”, “Z” | out-File $qFileName -Encoding OEM

To replace just end of the line, I attempted to change my code to:
$qFile -replace “,ABC:A`n”, “Z`n” | out-File $qFileName -Encoding OEM

But that did not help - no replacement is done at all.
How could I adjust my script so that replacement would be done just for string that is at the end of each line?

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…

David F.

David F.,

Thank you very much for your answer! I spend hours trying to figure this out.

Thank you!