[英]powershell escaping the escape character in a replace
更新 - 尝试过没有任何反勾的文本仍然没有替换。
我有一个包含这些记录的文件 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 和替换文本以及需要转义字符的文章。 我以为我做了需要的事情,但没有任何东西被替换。
如何替换包含反勾号的文本?
看起来当在批处理脚本中使用替换并且文本包含反勾号字符或双引号时,那么所有反勾号和双引号都需要在批处理脚本中转义。 原来的 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""
如果字符串中有反勾号,则反勾号也必须使用反斜杠进行转义,例如
\`
批处理脚本真是一团糟。 谢谢你帮我解决这个问题。
我认为你的命令有错误,这就是它没有改变的原因。 您错过了 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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.