【发布时间】:2020-07-27 18:45:04
【问题描述】:
我需要使用 PowerShell 编辑 txt 文件。问题是,仅当字符串的其余部分与某些模式匹配时,我才需要对字符串应用更改。例如,仅当行以 '模式':
'specific_text and pattern' -> changes to 'other_text and pattern'
但如果该行不以pattern结尾,我不需要更改它:
'specific_text and something else' -> no changes
我知道 PowerShell 中的 Replace 函数,但据我所知,它对正则表达式的所有匹配项进行了简单的更改。还有 Select-String 功能,但我无法正确组合它们。我的想法是这样:
((get-content myfile.txt | select-string -pattern "pattern") -Replace "specific_text", "other_text") | Out-File myfile.txt
但是这个调用会重写整个文件并且只留下改变的行。
【问题讨论】:
-
-Replace "specific_text(?=.*pattern$)", "other_text" -
谢谢你,@WiktorStribiżew!如果你愿意,你可以把它写成答案,我会接受它
标签: regex powershell