Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

LINE OF TEXT I NEED TO REPLACE

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

POTENTIAL CODE

(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.

like image 707
Jim P. Avatar asked Mar 16 '23 01:03

Jim P.


1 Answers

XML is not a line oriented format (nodes may span several lines, just as well as a line may contain several nodes), so it shouldn't be edited as if it were. Use a proper XML parser instead.

$xmlfile = 'C:\path\to\your.xml'

[xml]$xml = Get-Content $xmlfile
$node = $xml.SelectSingleNode('//find-this-text')
$node.'#text' = 'replacement text'

For saving the XML in "UTF-8 without BOM" format you can call the Save() method with a StreamWriter doing The Right Thing™:

$UTF8withoutBOM = New-Object Text.UTF8Encoding($false)
$writer = New-Object IO.StreamWriter ($xmlfile, $false, $UTF8withoutBOM)
$xml.Save($writer)
$writer.Close()
like image 56
Ansgar Wiechers Avatar answered Mar 25 '23 00:03

Ansgar Wiechers