Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace literal strings in Powershell?

Tags:

powershell

I have this code where I can't seem to backslash the find/replace strings correctly:

$find = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
$replace = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.2 Safari/537.36"

Get-Content prefs.js | %{ $_ -replace  $find, $replace } | Set-Content prefs.js

The $find value isn't being replaced by the $replace value when this is run.

like image 918
JohannesTK Avatar asked Jun 18 '14 13:06

JohannesTK


People also ask

How do I replace a string in PowerShell?

You don't need to assign a string to a variable to replace text in a string. Instead, you can invoke the replace() method directly on the string like: 'hello world'. replace('hello','hi') . The tutorial is using a variable for convenience.

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

Replace Multiple Instance Strings Using the replace() Function in PowerShell. Since the replace() function returns a string, to replace another instance, you can append another replace() function call to the end. Windows PowerShell then invokes the replace() method on the original output.

How do I change the path in PowerShell?

You can also change directory in PowerShell to a specified path. To change directory, enter Set-Location followed by the Path parameter, then the full path you want to change directory to. If the new directory path has spaces, enclose the path in a double-quote (“”).

How do I remove special characters from a string in PowerShell?

Use the -Replace Operator to Escape Special Characters in PowerShell. The -Replace operator replaces texts or characters in PowerShell. You can use it to remove texts or characters from the string. The -Replace operator requires two arguments: the string to find and the string to replace from the given input.


1 Answers

It looks like you deal with literal strings. Do not use the -replace operator which deals with regular expressions. Use the Replace method:

... | %{$_.Replace("string to replace", "replacement")} | ...

Alternatively, if you still want to use -replace then also use [regex]::Escape(<string>). It will do the escaping for you.

Example: replacing text literally with "$_"

Compare the results of the following, showing what can happen if you use an automatic variable in a regex replacement:

[PS]> "Hello" -replace 'll','$_'                  # Doesn't work!
HeHelloo

[PS]> "Hello".Replace('ll','$_')                  # WORKS!
He$_o
like image 148
Roman Kuzmin Avatar answered Oct 30 '22 12:10

Roman Kuzmin