Kangaroo
Kangaroo

Reputation: 125

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

I have a text file that contains a like that is similar to

Settings amount ="01:00:00"

I know how to replace the line but my issue is at the moment I am only able to replace the entire line if I know the exact contents of the line- using -match and -replace. However, is there a way that I can search for just Settings amount = and then just replace that entire line with my new setting? That way no matter what the current value is I have the power to scan and give it a different value.

This is what I have currently.

$DesiredTime = 'Settings amount="06:00:00" />'

$path = "C:\Windows\File.txt" 
 (Get-Content $path) -replace 'Settings amount="01:00:00" />', $DesiredTime | out-file $path

Any ideas?

Upvotes: 12

Views: 28281

Answers (2)

Bryan Kerwin
Bryan Kerwin

Reputation: 111

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

}

Upvotes: 11

StephenP
StephenP

Reputation: 4081

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.

Upvotes: 24

Related Questions