Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

powershell - 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:WindowsFile.txt" 
 (Get-Content $path) -replace 'Settings amount="01:00:00" />', $DesiredTime | out-file $path

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:empest.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:empest.txt
$content | ForEach-Object {$_ -replace $line,"pear = amazing"} | Set-Content c:empest.txt

Confirm the changes

Get-Content C:empest.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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...