You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 01:05:18