如何在PowerShell中转义和替换反斜杠字符 '\'

3
我们希望在我们的主文件中将\替换为\\,这可以防止在Redshift上上传(一旦替换为\\,就可以无问题地上传,并且它将上传单个\,与原始客户数据相同)。
我尝试按以下方式将\替换为\\,但在PowerShell中收到了一个正则表达式错误:
Param(
    [string]$TargetFileName
)

# replace words
$old='`\'
$new='`\`\'

# replace \ to \\ for Redshift upload
$file_contents=$(Get-Content "$TargetFileName") -replace $old,$new
$file_contents > $StrExpFile

错误信息:

+ $file_contents=$(Get-Content "$TargetFileName") -replace $old,$new
+                  ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (`\:String) []、RuntimeException
    + FullyQualifiedErrorId : InvalidRegularExpression

仅仅使用 -replace '\','\\' 并没有起作用。

我们希望将其保存为相同的文件名,但是文件大小可能会很大,如果您有更好的想法,也会非常感激。


3
你也可以使用内置的正则表达式转义方法。这个 [regex]::Escape() 方法会接收一个字符串并添加必要的转义字符,不需要手动解析它... [咧嘴笑] - undefined
1
@Lee_Dailey,非常感谢你又提出了一个绝妙的想法。多亏了你,我对PowerShell更感兴趣了,实际上它可以为我们提供很多选择 :) - undefined
1
非常欢迎...我很高兴能够帮助![微笑] - undefined
2个回答

6

-Replace 使用正则表达式,在正则表达式中 \ 是一个特殊字符(转义字符),所以要转义单斜杠需要使用另一个斜杠:\\。请注意,这仅对于 $old(您想匹配的文本)有效。替换文本$new不是正则表达式,因此在这里仍然只需要使用\\

$old = '\\'
$new = '\\'
$file_contents = (Get-Content "$TargetFileName") -replace $old,$new

或者,您可以使用.replace()方法,它不使用正则表达式:

$old = '\'
$new = '\\'
$file_contents = (Get-Content "$TargetFileName").replace($old,$new)

1
马克,非常感谢,两者都像我们所期望的那样工作!! 并且非常感谢你提供的另一种更简单的方法 :) 我真的很感激像你这样在Stackoverflow的专家总是帮助我。 - undefined

0

我使用一个带参数的命令,它会将 store:Schema="abcd" 替换为空字符串,我将 " 转义为 """""",如下:

powershell -Command "$varStr='store:Schema=""abcd""""'; $filePath='%~dp0SomeFolder\SomeFile.txt'; (gc $filePath) -replace $varStr, '' | Out-File $filePath"

1
非常抱歉回复晚了,但我真的非常感谢你的有用建议。谢谢! - undefined

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