Author Posts

May 31, 2017 at 1:04 am

Hello,

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:

1,3,ABC:A
1,4,BD:X
1,5,ABC:ACN
1,6,ABC:A

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?

May 31, 2017 at 3:23 am

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.

May 31, 2017 at 11:23 am

David F.,

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

Thank you!