Replace an entire line of text with powershell and regexp?

I have a programming background, but I'm pretty new to powershell and regexp scripting. Regexp has always eluded me, and my previous projects have never "forced" me to learn it.

With this in mind, I have a text file that I need to replace. I cant depend on where the line will exist if there is a space before it or that the text being replaced is ACTUAL. I KNOW there will be a foreword and preceding the text to be replaced.

AGAIN I DON'T KNOW the meaning of "Replace this text". I will only know that the foreword is "and what implements it." Edited by the OP for clarification. Thanks!

LINE OF TEXT THAT NEEDS TO REPLACE

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

      

POTENTIAL CODE

(gc $file) | % { $_ -replace "", "" } | sc $file

      

  • Get the contents of the file, enclose it in parentheses to make sure the file is read first and then closed, so it doesn't throw an error when trying to save the file.

  • Iterate over each line and issue a replace statement. THIS IS WHERE I CAN USE HELP.

  • Save the file using Set-Content. I understand that this method is preferable as it respects encoding, such as UTF8.

+3


source to share


2 answers


XML is not a line-oriented format (nodes can span multiple lines, just as a string can contain multiple nodes), so it cannot be edited as if it were. Use your own XML parser instead.

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

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

      



To save XML in "UTF-8 no BOM" format, you can call the method Save()

with StreamWriter

do the right thing and trade ;:

$UTF8withoutBOM = New-Object Text.UTF8Encoding($false)
$writer = New-Object IO.StreamWriter ($xmlfile, $false, $UTF8withoutBOM)
$xml.Save($writer)
$writer.Close()

      

+4


source


... * in a regular expression would be considered "greedy" and dangerous for many. If the string containing this tag and the data does not contain anything else, then in my understanding there really is no significant risk.



$file = "c:\temp\sms.txt"
$OpenTag = "<find-this-text>"
$CloseTag = "</find-this-text>"
$NewText = $OpenTag + "New text" + $CloseTag

(Get-Content $file) | Foreach-Object {$_ -replace "$OpenTag.*$CloseTag", $NewText} | Set-Content $file

      

+2


source







All Articles