2

假设我有一个名为 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"}

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

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

one two three

然后将此处的字符串相应地更改为:

$herestring1 = @"
one two three
"@

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

然后它可以正常工作,我可以根据需要替换字符串。

4

2 回答 2

1

正如 Martin 指出的那样,您可以使用-SimpleMatchwithSelect-String来避免将其解析为正则表达式。

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

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

$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"

于 2016-10-17T14:46:38.547 回答
0

只需使用带有开关的Select-Stringcmdlet :-SimpleMatch

# ....
if((Get-Content testfile.txt) | select-string -SimpleMatch $herestring1) {
# ....

-简单匹配

指示 cmdlet 使用简单匹配而不是正则表达式匹配。在简单匹配中,Select-String 在输入中搜索 Pattern 参数中的文本。它不会将 Pattern 参数的值解释为正则表达式语句。

资源。

于 2016-10-17T14:42:20.897 回答