从文件中删除子串到行尾

时间:2017-10-13 08:51:22

标签: regex powershell wildcard

考虑文件dummy.txt,如下所示:

SomeMessage: "BLABLABLA Value 'V1' of attribute 'CLR', Additional Information: 'Sometext'."
SomeMessage: "BLABLABLA Value 'W2' of attribute 'HGT', Additional Information: 'Sometextmore'."
SomeMessage: "BLABLABLA Value 'X3' of attribute 'SND', Additional Information: 'EvenSomeBiggerBulk'."

如何从以", Additional Information"开头直到行末的每行删除每个子字符串?这样我得到以下结果:

SomeMessage: "BLABLABLA Value 'V1' of attribute 'CLR'
SomeMessage: "BLABLABLA Value 'W2' of attribute 'HGT'
SomeMessage: "BLABLABLA Value 'X3' of attribute 'SND'

我试过了:

(Get-Content dummy.txt).Replace(', Additional*." ', '') | Set-Content temp.txt 

但这使文件保持不变。

2 个答案:

答案 0 :(得分:4)

你几乎是正确的

(Get-Content dummy.txt) -replace ", Additional.*" | Set-Content temp.txt 

而不是.NET String方法.Replace(),它使用PowerShell运算符-replace

.NET方法接受两个字符串oldValuenewValue,并且不使用正则表达式。它只能取代完全匹配。

PowerShell运算符也接受两个字符串,但它使用正则表达式。如果您只想删除匹配项,newValue字符串是可选的。

答案 1 :(得分:2)

我会选择:

(Get-Content dummy.txt) -replace (",\sAdditional.*", "") > temp.txt

我更喜欢>重定向器(管道也可以正常工作)。我改进了regex以匹配您要搜索的内容。

相关问题