powershell - 查找并替换同时包含双引号和方括号的字符串

标签 powershell replace select-string herestring

假设我有一个名为testfile.txt的测试文件,其中包含以下行:

one (two) "three"

我想使用PowerShell来说,如果整个字符串都存在,则在该字符串的正下方放置一个带有值的行:
four (five) "six" 

(请注意,它同时包含空格,方括号和双引号。这很重要,因为我遇到的问题是转义方括号和双引号)。

因此结果将是:
one (two) "three"
four (five) "six" 

我认为最简单的方法是说,如果找到了第一个字符串,请再次用第一个字符串本身替换它,并且新字符串构成同一命令中的新行。我很难将字符串放在一行中,因此我尝试使用herestring变量,从而读取具有格式的整个文本块。它仍然不会将带有引号的完整字符串解析到管道中。我是Powershell的新手,所以如果您看到愚蠢的东西,请不要退缩。
$herestring1 = @"
one (two) "three"
"@

$herestring2 = @"
one (two) "three"
four (five) "six"
"@

if((Get-Content testfile.txt) | select-string $herestring1) {
"Match found - replacing string"
(Get-Content testfile.txt) | ForEach-Object { $_ -replace $herestring1,$herestring2 } | Set-Content ./testfile.txt
"Replaced string successfully"
}
else {
"No match found"}

上面每次都给出“找不到匹配项”。这是因为它找不到文件中的第一个字符串。
我曾尝试使用反引号[`]和双引号来尝试变体,以进行转义,但我认为here字符串中的要点是它应该解析文本块,包括所有格式,因此我不必这样做。

如果我将文件更改为仅包含:
one two three

然后相应地将herestring更改为:
$herestring1 = @"
one two three
"@

$herestring2 = @"
one two three
four five six
"@

然后就可以了,我可以根据需要替换字符串。

最佳答案

正如Martin所指出的,可以将-SimpleMatchSelect-String一起使用,以避免将其解析为正则表达式。

但是-replace仍将使用正则表达式。

您可以使用[RegEx]::Escape()转义RegEx的模式:

$herestring1 = @"
one (two) "three"
"@

$herestring2 = @"
one (two) "three"
four (five) "six"
"@

$pattern1 = [RegEx]::Escape($herestring1)

if((Get-Content testfile.txt) | select-string $pattern1) {
"Match found - replacing string"
(Get-Content testfile.txt) | ForEach-Object { $_ -replace $pattern1,$herestring2 } | Set-Content ./testfile.txt
"Replaced string successfully"
}
else {
"No match found"}

正则表达式将括号()(您称为方括号)解释为特殊括号。默认情况下,空格不是特殊的,但可以带有某些正则表达式选项。双引号没问题。

在正则表达式中,转义字符为反斜杠\,这与您使用backtick `对PowerShell解析器所做的任何转义无关。
[RegEx]::Escape()将确保对正则表达式进行特殊处理,以使正则表达式模式将其解释为文字,因此您的模式最终将如下所示:one\ \(two\)\ "three"

关于powershell - 查找并替换同时包含双引号和方括号的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40089257/

相关文章:

azure - 通过 Azure powershell 命令远程运行 SysPrep

Powershell 获取列出的值

javascript - javascript中以下正则表达式的含义是什么

regex - Select-String:仅当字符串前面没有特定字符时才匹配字符串

powershell - 在PowerShell中将Refresh()发送到WMI

powershell - 递归函数中属性值的缩短输出

c# - C#中的递归字符串替换

python - 如何在没有循环的情况下交换字符串中的值

regex - 捕获组在 Select-String 的 -Pattern 末尾不起作用

powershell - 在文本文件中搜索字符串,但得到多个结果