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?
The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.
To replace a line in a file, use PowerShell replace() method that takes two arguments; string to find and string to replace with found text. After the replacement of a line in a file, pipe the output to the Set-Content cmdlet to save the file.
sed -i 's/old-text/new-text/g' input. txt. The s is the substitute command of sed for find and replace.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With