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

如何用awk将0.txt中两字符串间第n次出现的内容替换为1.txt的第n行

正确实现代码

适配GNU Awk 4.0+版本(大部分Linux系统默认版本)

awk '
NR == FNR {
    rep[FNR] = $0
    rep_cnt = FNR
    next
}
{
    if (match($0, /(.*group_tree\()(.*)(\)\t",.*)/, grp)) {
        idx = ++n % rep_cnt
        idx = idx == 0 ? rep_cnt : idx
        print grp[1] rep[idx] grp[3]
    } else {
        print $0
    }
}
' 1.txt 0.txt > 2.txt

全版本兼容写法(适配macOS自带awk等旧版本)

awk '
NR == FNR {
    rep[FNR] = $0
    rep_cnt = FNR
    next
}
{
    if (match($0, /.*group_tree\(/)) {
        pre = substr($0, 1, RSTART + RLENGTH - 1)
        rest = substr($0, RSTART + RLENGTH)
        if (match(rest, /\)\t",.*/)) {
            idx = ++n % rep_cnt
            idx = idx == 0 ? rep_cnt : idx
            print pre rep[idx] substr(rest, RSTART)
            next
        }
    }
    print $0
}
' 1.txt 0.txt > 2.txt

逻辑说明

  1. 先读取1.txt的所有行存入rep数组,同时记录1.txt的总行数rep_cnt
  2. 处理0.txt时,用正则拆分出group_tree(前的固定内容、中间待替换内容、)\t",后的固定内容三部分
  3. 每次匹配到目标行时对计数取模,超出1.txt行数时自动循环取内容
  4. 未匹配到目标格式的行直接原行输出,完全匹配你给出的预期输出效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:06:03