如何用sed替换指定pattern后首个myString为replacement_pattern
使用sed实现指定位置的字符串替换
需求说明
现有输入文件内容:
new file myString abc myString xyz pattern file txt myString almost the end of file myString end of file
需要仅替换pattern之后出现的第一个myString为replacement_pattern,pattern与目标myString之间的行数不固定,最终输出如下:
new file myString abc myString xyz pattern file txt replacement_pattern almost the end of file myString end of file
解决方案
使用以下sed命令即可完成需求:
sed '/pattern/{:loop;n;s/myString/replacement_pattern/;Tloop}' input.txt
命令解释
/pattern/{...}:定位到包含pattern的行,执行大括号内的逻辑:loop:定义一个名为loop的标签,用于循环跳转n:读取下一行内容到sed的模式空间s/myString/replacement_pattern/:尝试将当前行的myString替换为目标字符串Tloop:如果上一步的替换操作未成功(即当前行不是myString),就跳转到loop标签继续读取下一行;一旦替换成功,就退出循环,继续处理后续行
这样就能精准替换pattern之后的第一个myString,不影响前后其他位置的匹配项。
内容的提问来源于stack exchange,提问作者The Warrior
相关产品推荐
相关产品推荐

