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

使用AWK替换Markdown指定标签间多行内容的问题求助

解决Markdown指定区间内容替换的AWK方案

核心思路

放弃用gsub处理多行复杂内容(单行正则无法可靠匹配跨多行区间),改用状态机模式:识别起始/结束标记,仅在两个标记之间替换为新内容,其余部分原样输出。

实现脚本

假设新的Kubernetes集群信息已生成并保存到new_kube_content.txt,待处理的Markdown文件为cluster_report.md,以下是AWK脚本:

BEGIN {
    # 预读取新内容,保留完整格式
    while ((getline line < "new_kube_content.txt") > 0) {
        new_content = new_content line "\n"
    }
    close("new_kube_content.txt")
    in_target = 0  # 标记是否处于目标替换区间
}

# 匹配起始标记,输出标记后直接插入新内容
/^# Kube_cluster$/ {
    print $0
    in_target = 1
    printf "%s", new_content
    next
}

# 匹配结束标记,输出标记并退出替换状态
/^---<br><br>$/ {
    if (in_target) {
        print $0
        in_target = 0
        next
    }
}

# 非目标区间的内容原样输出
!in_target { print $0 }

使用方式

将脚本保存为replace_kube.awk,执行以下命令完成替换:

awk -f replace_kube.awk cluster_report.md > temp_report.md && mv temp_report.md cluster_report.md

也可以直接在命令行内执行(无需单独保存脚本):

awk '
BEGIN {
    while ((getline line < "new_kube_content.txt") > 0) {
        new_content = new_content line "\n"
    }
    close("new_kube_content.txt")
    in_target = 0
}
/^# Kube_cluster$/ {
    print $0
    in_target = 1
    printf "%s", new_content
    next
}
/^---<br><br>$/ {
    if (in_target) {
        print $0
        in_target = 0
        next
    }
}
!in_target { print $0 }
' cluster_report.md > temp.md && mv temp.md cluster_report.md

扩展优化

  1. 兼容标记前后空格:如果起始/结束标记前后可能有空格,修改正则为:
    • 起始标记:/^[[:space:]]*# Kube_cluster[[:space:]]*$/
    • 结束标记:/^[[:space:]]*---<br><br>[[:space:]]*$/
  2. 实时生成新内容:如果不需要提前保存文件,可直接在BEGIN块中执行命令获取K8s信息:
    BEGIN {
        cmd = "kubectl get nodes -o markdown && kubectl get pods -n kube-system -o markdown"
        while ((getline line < cmd) > 0) {
            new_content = new_content line "\n"
        }
        close(cmd)
        in_target = 0
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 13:10:34