【发布时间】:2021-05-05 15:04:53
【问题描述】:
我正在使用此post 中代码的修改版本。
$fileToCheck = "c:\Users\me\desktop\test.txt"
$fileContents = Get-Content $fileToCheck
$line = $fileContents | Select-String "hosts" | Select-Object -ExpandProperty Line
if ($line -eq $null) {
"String Not Found"
exit
}
echo $line
$modifiedContents = $fileContents | ForEach-Object {$_ -replace $line,'hey'}
echo $modifiedContents
这是我的test.txt 文件内容:
X.Y:
hosts: ["https://localhost:111"]
hosts 前面有 2 个空格。
我无法更换线路。我已将其范围缩小到这可能是由于该行中使用的特殊字符之一导致了问题。
我已经用原始数据尝试了修改后的代码,一切正常。
不确定我的情况是什么?
非常感谢您的宝贵时间。
【问题讨论】:
-
如果您的目标是将整行
' hosts: ["https://localhost:111"]'替换为值hey,那么您需要使用[regex]::Escape($line)转义特殊字符。你能告诉我们想要的输出吗? -
@Theo 想要的输出实际上是`hosts: ["a.b.c.d:111"]`。非常感谢!
-
简而言之:PowerShell 的
-replaceoperator 默认是基于regex 且大小写不敏感。要执行 literal 替换,\-escape 模式中的元字符或调用[regex]::Escape()。相比之下,[string]类型的.Replace()方法 执行literal 替换,并且区分大小写,始终在 Windows PowerShell 中,默认在 PowerShell(核心)中。请参阅answer to the linked duplicate。
标签: powershell