Forum Discussion
nancyvargas
Dec 21, 2022Copper Contributor
Powershell - string replacement using regex
Hi All, I need help in powershell string replacement using regex. I need to replace a decimal value after a specific string pattern with a new decimal value stored in a variable. Like, in the entir...
RGijsbersRademakers
Dec 21, 2022Iron Contributor
Hi nancyvargas,
You can use one of the following methods
- First, define the variables for the old value ("xxx") and the new value:
$OldValue = "xxx"
$NewValue = "your new value here"
Next, use the Replace() method to find and replace all occurrences of the old value with the new value in a string:
$string = "some string with Version=xxx and other text"
$string = $string.Replace($OldValue, $NewValue) - You can also use the -replace operator to do the same thing:
$string = "some string with Version=xxx and other text"
$string = $string -replace $OldValue, $NewValue - If you want to replace all occurrences of "Version=xxx" in a file, you can use the Get-Content cmdlet to read the file into a string, then use the Replace() method or -replace operator as shown above to replace the old value with the new value:
$fileContent = Get-Content "C:\path\to\your\file.txt"
$fileContent = $fileContent.Replace($OldValue, $NewValue)
or
$fileContent = Get-Content "C:\path\to\your\file.txt"
$fileContent = $fileContent -replace $OldValue, $NewValue
Finally, use the Set-Content cmdlet to write the modified string back to the file:
Set-Content "C:\path\to\your\file.txt" -Value $fileContent
I hope this helps.
Regards,
Ruud