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

如何在Bash中替换指定单词后首个目标行内容

解决Bash中替换指定单词后首个目标行的问题

原始文件内容

"text1"
{
    "text2" "0"
    "text3" "0"
    "text4" "0"
    "text5" "0"
    "text6" "0"
}
"text11"
{
    "text2" "0"
    "text3" "0"
    "text4" "0"
    "text5" "0"
    "text6" "0"
}
"text21"
{
    "text2" "0"
    "text3" "0"
    "text4" "0"
    "text5" "0"
    "text6" "0"
}

目标结果

"text1"
{
    "text2" "0"
    "text3" "0"
    "text4" "0"
    "text5" "0"
    "text6" "0"
}
"text11"
{
    "text2" "0"
    "text3" "0"
    "text4" "0"
    "REPLACED TEXT" "1"
    "text6" "0"
}
"text21"
{
    "text2" "0"
    "text3" "0"
    "text4" "0"
    "text5" "0"
    "text6" "0"
}

解决方案:使用awk命令

可以通过awk实现精准匹配替换,它能跟踪状态,只替换"text11"之后的第一个"text5"行:

awk '/"text11"/ {flag=1} flag && /"text5"/ {print "    \"REPLACED TEXT\" \"1\""; flag=0; next} 1' input_file > output_file

命令解释

  • /\"text11\"/ {flag=1}:当匹配到"text11"行时,设置标记变量flag为1,表示后续开始寻找目标行
  • flag && /\"text5\"/ {...}:当flag为1且当前行匹配"text5"时,执行替换操作:
    • 打印替换后的内容" \"REPLACED TEXT\" \"1\""
    • 将flag重置为0,避免替换后续其他"text5"行
    • next跳过当前行的默认输出
  • 1:默认打印所有未被特殊处理的行

如果需要直接修改原文件,可以结合sponge命令(需安装moreutils包):

awk '/"text11"/ {flag=1} flag && /"text5"/ {print "    \"REPLACED TEXT\" \"1\""; flag=0; next} 1' input_file | sponge input_file

或者使用GNU awk的-i inplace选项直接编辑原文件:

awk -i inplace '/"text11"/ {flag=1} flag && /"text5"/ {print "    \"REPLACED TEXT\" \"1\""; flag=0; next} 1' input_file

内容的提问来源于stack exchange,提问作者Paweł Selen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 13:30:12