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

This topic contains 2 replies, has 2 voices, and was last updated by  jrrbujfl 11 months, 3 weeks ago.

  • Author
  • #71749



    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?

  • #71758


    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.

  • #71767


    David F.,

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

    Thank you!

You must be logged in to reply to this topic.