从文件中删除子字符串到行尾
Delete substring from file to end of line
考虑文件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
但这会使文件保持不变。
你几乎是正确的
(Get-Content dummy.txt) -replace ", Additional.*" | Set-Content temp.txt
它使用 PowerShell 运算符 -replace
.
而不是 .NET String 方法 .Replace()
.NET 方法接受两个字符串,oldValue
和 newValue
,并且不使用正则表达式。它只能替换完全匹配。
PowerShell 运算符也接受两个字符串,但它使用正则表达式。如果您只想删除匹配项,则 newValue
字符串是可选的。
我会选择:
(Get-Content dummy.txt) -replace (",\sAdditional.*", "") > temp.txt
我更喜欢 >
重定向器(管道也可以正常工作)。我改进了 regex
以匹配您正在搜索的内容。
考虑文件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
但这会使文件保持不变。
你几乎是正确的
(Get-Content dummy.txt) -replace ", Additional.*" | Set-Content temp.txt
它使用 PowerShell 运算符 -replace
.
.Replace()
.NET 方法接受两个字符串,oldValue
和 newValue
,并且不使用正则表达式。它只能替换完全匹配。
PowerShell 运算符也接受两个字符串,但它使用正则表达式。如果您只想删除匹配项,则 newValue
字符串是可选的。
我会选择:
(Get-Content dummy.txt) -replace (",\sAdditional.*", "") > temp.txt
我更喜欢 >
重定向器(管道也可以正常工作)。我改进了 regex
以匹配您正在搜索的内容。