Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace substring in PowerShell

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?

like image 864
Lars Natus Avatar asked Feb 16 '13 17:02

Lars Natus


People also ask

How do I replace a Substring 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.

How do I replace a word in a string in PowerShell?

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.

How do I replace multiple characters in a string in PowerShell?

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.

How do I replace a line in PowerShell?

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.


1 Answers

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)
like image 84
Roger Lipscombe Avatar answered Oct 22 '22 20:10

Roger Lipscombe