Replace an entire line of text using powershell and regexp?

I have a programming background, but I am fairly new to both powershell scripting and regexp. Regexp has always eluded me, and my prior projects have never ‘forced’ me to learn it.

With that in mind I have a file with a line of text that I need to replace. I can not depend on knowing where the line exists, if it has whitespace in front of it, or what the ACTUAL text being replaced IS. I DO KNOW what will preface and preceed the text being replaced.

AGAIN, I will not KNOW the value of “Replace This Text”. I will only know what prefaces it “” and what preceeds it “”. Edited OP to clarify. Thanks!


<find-this-text>Replace This Text</find-this-text>


(gc $file) | % { $_ -replace “”, “” } | sc $file
  • Get the content of the file, enclose this in parentheses to ensure file is first read and then closed so it doesnt throw an error when trying to save the file.

  • Iterate through each line, and issue replace statement. THIS IS WHERE I COULD USE HELP.

  • Save the file by using Set-Content. My understanding is that this method is preferable, because it takes encoding into consideration,like UTF8.

Source: regex

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.