I have a string in the form -content-
, and I would like to replace it with &content&
. How can I do this with replace in PowerShell?
To do this, we will use the Replace operator. The Replace operator works just like the Match operator. The syntax is input string, operator, match pattern, replacement string.
You can call the PowerShell replace method on any string to replace any literal string with another. If the string-to-be-replaced isn't found, the replace() method returns nothing. You don't need to assign a string to a variable to replace text in a string.
You can replace multiple characters in a string using PowerShell replace() method or PowerShell replace operator. If you are using the PowerShell replace() method, you can chain replace() method as many times to replace the multiple characters in the PowerShell string.
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.
PowerShell strings are just .NET strings, so you can:
PS> $x = '-foo-'
PS> $x.Replace('-', '&')
&foo&
...or:
PS> $x = '-foo-'
PS> $x.Replace('-foo-', '&bar&')
&bar&
Obviously, if you want to keep the result, assign it to another variable:
PS> $y = $x.Replace($search, $replace)
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