【问题标题】:powershell escaping the escape character in a replacepowershell在替换中转义转义字符
【发布时间】:2015-10-26 06:20:04
【问题描述】:

更新 - 没有任何反引号的尝试文本仍未替换。

我有一个包含这些记录的文件 test.txt:

name="BLUE_TBL_AC_EA_FREQ"` owner="BLUE_TBL_AC_EA_FREQ"
name="BLUE_TBL_AC_EA_FREQ" owner="RED_TBL_AC_EA_FREQ"

我想替换 name 属性的字符串,所以我会使用

name="BLUE_TBL_AC_EA_FREQ"

在 powershell 脚本中。这就是我所做的,但输出文件不包含替换的文本,它与输入相同。

然后我使用批处理脚本,在批处理脚本中有这个 powershell 命令

powershell -Command "(Get-Content "test.txt") | Foreach-Object {$_ -replace 'name="BLUE_TBL_AC_EA_FREQ"', 'name="BLUE_TBL_ACEAFREQ"'} | Set-Content "testo.txt""

批处理脚本不会替换包含该字符串的字符串。 我做错了什么,我是否必须转义字符串的双引号? 它仍然不适合我。

结束更新

我正在尝试使用 Powershell 替换文件中使用反引号的一些文本。 在文件中有诸如

之类的文字

'name="BLUE_TBL_AC_EA_`FREQ"' 我想把这段文字替换为

' name="BLUE_TBL_ACEAFREQ"'

我在 Powershell 中使用的替换看起来像这样

powershell -command "& {(Get-Content "file.txt") | Foreach-Object {$_ -replace ' name="BLUE_TBL_AC_EA_`FREQ"', ' name="BLUE_TBL_ACEAFREQ"'} | Set-Content "fileO.txt;}"

'name= 是必需的,因为有多个字符串包含 name="... 字符串。

当我使用这个命令时,没有任何东西被替换。我试图通过使用双反勾号(``)来逃避反勾号,但仍然没有任何东西被替换。 我已经搜索并阅读了许多关于 Powershell 和替换文本以及转义字符的需要的文章。我以为我做了需要做的事,但没有任何东西被替换。

如何替换包含反引号的文本?

【问题讨论】:

  • 问题可能是通过-command参数传递脚本引起的。所有的引号都可能把事情搞砸了。最好将脚本放在一个文件中。
  • 我想通了。双引号和反引号必须在批处理脚本中转义。 PS 的替换字符串最终是 {$_ -replace ' name=\"BLUE_TBL_AC_EA_`FREQ\"', ' name=\"BLUE_TBL_ACEAFREQ\"'} 然后它是否适用于反勾号。谢谢你帮助我。

标签: string powershell replace escaping


【解决方案1】:

看起来,当在批处理脚本中使用替换并且文本包含反引号字符或双引号时,则需要在批处理脚本中对所有反引号和双引号进行转义。

的 powershell 命令
powershell -Command "(Get-Content "test.txt") | Foreach-Object {$_ -replace 'name="BLUE_TBL_AC_EA_FREQ"', 'name="BLUE_TBL_ACEAFREQ"'} | Set-Content "testo.txt""

变成:

powershell -Command "(Get-Content "test.txt") | Foreach-Object {$_ -replace 'name=\"BLUE_TBL_AC_EA_FREQ\"', 'name=\"BLUE_TBL_ACEAFREQ\"'} | Set-Content "testo.txt""

如果字符串中有反引号,那么反引号也必须使用反斜杠进行转义,例如

\`

批处理脚本真是一团糟。 感谢您帮助我解决这个问题。

【讨论】:

    【解决方案2】:

    我认为您的命令有错误,这就是它没有更改的原因。您错过了 txt 后分号前的双引号。

    我在我的 powershell 中尝试了这个,它正在工作。

    (Get-Content "C:\test.txt") | Foreach-Object {$_ -replace ' name="BLUE_TBL_AC_EA_`FREQ"', ' name="BLUE_TBL_ACEAFREQ"'} | Set-Content "C:\test.txt"
    

    【讨论】:

      猜你喜欢
      • 2010-10-07
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-17
      • 2012-04-07
      • 1970-01-01
      • 2021-06-20
      相关资源
      最近更新 更多