Reputation: 419
How do I get Powershell regex to replace an entire line in a file from a match containing several keywords?
I have the following so far where the line to replace is already defined in the $search_parameter variable and the search keyword is a single word stored in the $namefile parameter:
(Get-Content "C:\path\txt.file") -replace "`^$namefile`"/>", $search_parameter | Set-Content "C:\path\txt.file"
I'm struggling with the regex to replace to extend from the beginning of the line to the $namefile variable and a few characters after it. I thought a ^ would do the trick, but since I'm dealing with strings and other characters, I don't think it'd work encapsulated in double-quotes.
Example config file:
<configuration-file>
<section name="section1">
<entry name="name1" value="value1"/>
<entry name="name2" value="value2"/>
</section>
<section name="section2">
<entry name="someothername" value="someothervalue"/>
</section>
</configuration-file>
So with the example config file, the $search_parameter would for instance be '428' and $namefile would be 'value2', but the -replace parameter would be set to expand to the entire line that 'value2' is based on. I got it to work without focusing on the entire line and just replacing 'value2', but I'm trying to replace and add other XML values as needed if that makes any sense.
Upvotes: 0
Views: 178
Reputation: 857
To put two and two together. From this link, here is what you were asking for... replacing "value2" with "428"
$Path = "C:\temp\testfile.txt"
$xml = [xml](get-content $Path)
($xml.'configuration-file'.section.entry | Where-Object {$_.value -eq "value2"}).value = '428'
$xml.Save("C:\temp\testfile_New.txt")
Here is the output of the new file:
<configuration-file>
<section name="section1">
<entry name="name1" value="value1" />
<entry name="name2" value="428" />
</section>
<section name="section2">
<entry name="someothername" value="someothervalue" />
</section>
</configuration-file>
Upvotes: 1