How to replace an entire line in text file by only knowing a portion of the line?

Take a look at Select-String. It will allow you to find the entire line that contains what you are looking for. Then you can update the line.

This is a sample file

apple = yummy
bananna = yummy
pear = awful
grapes = divine

Say I want to replace the line containing "pear". First get the line:

$line = Get-Content c:\temp\test.txt | Select-String pear | Select-Object -ExpandProperty Line

Now we just read in the content and replace the line with our line:

$content = Get-Content c:\temp\test.txt
$content | ForEach-Object {$_ -replace $line,"pear = amazing"} | Set-Content c:\temp\test.txt

Confirm the changes

Get-Content C:\temp\test.txt
apple = yummy
bananna = yummy
pear = amazing
grapes = divine

Note that if you are working with XML, which it looks like you might be you can open the document as an XML document and simply replace the attribute. Without seeing a sample of your source file its hard to tell.


Thanks for the code. Works well but just want to add that this goes bad if the string is not found at all. It will replace every line in your file. This fixed up my issue with that by checking for null:

$line = Get-Content c:\temp\test.txt | Select-String pear | Select-Object -ExpandProperty Line

if ($line -eq $null) {
"String Not Found"
exit
} else {
$content = Get-Content c:\temp\test.txt
$content | ForEach-Object {$_ -replace $line,"pear = amazing"} | Set-Content c:\temp\test.txt

}

Tags:

Powershell