【问题标题】:Replace line in file by only knowing part of line with PowerShell [duplicate]仅通过 PowerShell 知道部分行来替换文件中的行 [重复]
【发布时间】: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 的-replace operator 默认是基于regex 且大小写不敏感。要执行 literal 替换,\ -escape 模式中的元字符或调用 [regex]::Escape()。相比之下,[string] 类型的.Replace() 方法 执行literal 替换,并且区分大小写始终在 Windows PowerShell 中,默认在 PowerShell(核心)中。请参阅answer to the linked duplicate

标签: powershell


【解决方案1】:

我拿了你的脚本并将-replace 更改为.Replace(),它工作正常:

$modifiedContents = $fileContents | ForEach-Object {$_.Replace($line,'hey')}

您正在尝试进行文字替换,但您使用的是-replace,它涉及正则表达式,正如 Theo 在评论中建议的那样,如果您想坚持使用 -replace,则需要转义特殊字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 2015-12-20
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    相关资源
    最近更新 更多