Powershell:在文件中的字符串后追加文本

Powershell: append text after string in file

问题:我试图在标签后附加一个字符串。我有一个很大的文本文件,我只需要在标签后面追加一些文本(包括文本xxxxxx)<xxxxxx>,我似乎还没有弄明白。

目前我正在尝试使用正则表达式:<[(xxxxxx)]+>,根据 regex101.com 确实匹配确切的标签 <xxxxxx>,但是当我在 Powershell 中使用它时 returns很多其他的东西。

如何确保 Powershell 仅匹配 <xxxxxx>?并在 <xxxxxx> ?

之后附加一些字符串

文本文件中的示例片段:PredefinedSettings=<xxxxxx><abc test123 /abc></xxxxxx>

示例 PS 命令:Get-Content .\samplefile.ini | Select-String -Pattern "<[(xxxxxx)]+>"

returns 整行 PredefinedSettings=<xxxxxx><abc test123 /abc></xxxxx> 而不仅仅是 <xxxxxx>

希望我答对了你的问题。

在正则表达式中,量词是贪婪的,因此它将 select 从第一个开始标记到最后一个结束标记,您可以使用 ?.

来更改它

因此您的正则表达式将是 <[(xxxxxx)]+?>

如果你只想输出匹配的文本,你可以这样做:

Select-String -Path sample.ini -Pattern '<(/?xxxxxx)>' -AllMatches | Foreach-Object {
    $_.Matches.Groups[1].Value # Outputs matched text between `<>`
    $_.Matches.Value # Outputs all matched text
}

-AllMatches 开关将允许匹配超过第一个匹配项。所以它会 return <xxxxxx></xxxxxx>.


如果要替换文件中的文本,可以执行以下操作:

(Get-Content .\samplefile.ini) -replace '<(/?xxxxxx)>','<Text>' |
    Set-Content .\sampplefile.ini

如果您的替换文本在变量中,您将需要转义捕获组的 $

$Text = 'replacement Text'
(Get-Content .\samplefile.ini) -replace '<(/?xxxxxx)>',"<`$Text>" |
    Set-Content .\sampplefile.ini

</code> 是第一个 <code>() 中匹配的捕获组 1 数据。根据您的 Text,命名您的捕获组可能是明智的。如果 Text23OtherText<3OtherText> 将尝试替换捕获组 123。使用命名捕获组,您可以执行以下操作:

(Get-Content .\samplefile.ini) -replace '<(?<Tag>/?xxxxxx)>','<${Tag}Text>' |
    Set-Content .\sampplefile.ini

/? 匹配零个或多个 / 个字符。

-replace 将 return 所有不匹配的文本和所有由运算符替换的文本。