【问题标题】:How to replace lines depending on the remaining text in file using PowerShell如何使用 PowerShell 根据文件中的剩余文本替换行
【发布时间】: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


【解决方案1】:

你可以使用

(get-content myfile.txt) -replace 'specific_text(?=.*pattern$)', "other_text" | Out-File myfile.txt

specific_text(?=.*pattern$) 模式匹配

  • specific_text - 一些specific_text...
  • (?=.*pattern$) - 除了换行符之外,不要紧跟任何 0 个或多个字符,然后在字符串末尾添加 pattern ($)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    相关资源
    最近更新 更多