首页 > 解决方案 > 如何在 PowerShell 中转义和替换“\”

问题描述

我们想在我们的主文件中替换\to \\,这可以防止在 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 '\','\\'也没有用。

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

标签: powershell

解决方案


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

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

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

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

推荐阅读