powershell - 如何在 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 '\','\\'
也没有用。
我们希望将其保存为相同的文件名,但文件大小可能会很大,所以如果您有更好的想法,也将不胜感激。
解决方案
-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)
推荐阅读
- xctestcase - XCTestCases 是代码测试、功能测试还是功能测试?
- xcode - Xcode 卡在错误的 git 分支上
- android - 如何让 KotlinX 直接访问父活动的合成属性?
- python - Python如何使用熊猫数据框列从3个点获取角度
- mysql - 为什么我的 SQL 命令出现错误?
- c# - 以编程方式使用 docker 并捕获标准输出
- python - 如何在pyqt中创建一个滚动区域
- c++ - 从成员指针转换为整个结构/类
- google-kubernetes-engine - 如何让我的 Cloud Run(托管)应用程序访问我的 GKE 集群服务?
- vba - 为什么 VBA dim 语句的行为取决于声明的变量数量?