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

如何使用awk将文件内指定EOF包裹的文本块替换为其他文件内容

awk替换here-document块内容方案

核心原理

通过状态标记控制输出逻辑,精准匹配目标here-document的起止行,读取对应新文件内容替换原有块内内容,避开sed处理多行、特殊字符时的转义问题。

可直接执行的命令

awk '
# 匹配EOF1块起始行
/^cat << '\''EOF1'\'' > scriptfile1\.sh$/{
    print
    while((getline line < "file1.sh") > 0) print line
    close("file1.sh")
    skip1 = 1
    next
}
# 匹配EOF1块结束行
skip1 && /^EOF1$/{
    print
    skip1 = 0
    next
}
# 匹配EOF2块起始行
/^cat << '\''EOF2'\'' > scriptfile2\.sh$/{
    print
    while((getline line < "file2.sh") > 0) print line
    close("file2.sh")
    skip2 = 1
    next
}
# 匹配EOF2块结束行
skip2 && /^EOF2$/{
    print
    skip2 = 0
    next
}
# 非跳过区间正常输出
!skip1 && !skip2
' script.sh > script_modified.tmp && mv script_modified.tmp script.sh

说明

  • 命令执行完成后会直接覆盖原script.sh文件,如需备份可以在执行前先运行cp script.sh script.sh.bak
  • 严格匹配起止行的首尾字符,避免误匹配到块内的同名字符串
  • 支持替换文件内包含任意特殊字符,不会出现分隔符冲突、元字符转义错误的问题

内容的提问来源于stack exchange,提问作者swa056

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 21:36:02