如何在Powershell中替换文本字符串?

12

我有一段代码,在其中无法正确地对查找/替换字符串进行反斜线转义:

$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

当运行时,$find 值没有被 $replace 值替换。
1个回答

30

看起来你正在处理字面字符串。不要使用处理正则表达式的 -replace 运算符 。使用 Replace 方法:

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

另外,如果您仍然想使用 -replace,请同时使用 [regex]::Escape(<string>)。它将为您转义。

例如:直接用"$ _"替换文本

比较下面的结果,展示了在正则表达式替换中使用自动变量可能会发生的情况:

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

[PS]> "Hello".Replace('ll','$_')                  # WORKS!
He$_o

谢谢,通过使用该方法而不是正则表达式解决了我的问题! - Harvey Lin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接