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

求助:对比两个文件生成带标记输出文件(diff/awk/sed尝试未果)

解决两个文件内容对比并生成带标记输出的问题

先明确你的两个文件内容

File1:#4 and a row (2) +1 hello post (5) 10 Years After (6) 21 & Over (8) 50_50 (1) Almost Christmas (3)
File2:#4 and a row (2) http://example.com/post1 +1 hello post (5) http://example.com/post2 Not over yet (3) http://example.com/post12 10 Years After (6) http://example.com/post3

我的解决方案(用awk实现)

折腾了半天的diff、sed没搞定?试试这个awk脚本,直接运行就能生成带清晰标记的结果:

awk '
BEGIN {
    OFS = "\n"
    print "=== 仅在File1中存在的内容 ==="
}
NR == FNR {
    # 提取File1中所有带括号的完整条目,存入数组
    while (match($0, /[^ ]+ \([0-9]+\)/)) {
        item = substr($0, RSTART, RLENGTH)
        file1[item] = 1
        $0 = substr($0, RSTART + RLENGTH + 1)
    }
    next
}
{
    print "\n=== 仅在File2中存在的内容 ==="
    prev_item = ""
    # 处理File2,区分带括号条目和URL链接
    while (match($0, /([^ ]+ \([0-9]+\))|(http:\/\/example\.com\/[^ ]+)/)) {
        item = substr($0, RSTART, RLENGTH)
        if (item ~ /\([0-9]+\)/) {
            if (!file1[item]) {
                print "* " item " [仅File2有]"
            } else {
                common[item] = 1
            }
            prev_item = item
        } else {
            # 把URL关联到前面最近的条目,标记为新增链接
            print "* " prev_item " -> " item " [File2新增链接]"
        }
        $0 = substr($0, RSTART + RLENGTH + 1)
    }
    print "\n=== 两个文件共有的内容 ==="
    # 遍历File1条目,标记共同项和仅File1项
    for (item in file1) {
        if (common[item]) {
            print "* " item " [两个文件都有]"
        } else {
            print "* " item " [仅File1有]"
        }
    }
}' file1 file2

脚本说明

  • 第一步先把File1里的核心条目(带括号的内容)全存起来,作为对比基准
  • 处理File2时,自动区分普通条目和URL链接,URL会和前面对应的条目绑定,标记为“新增链接”
  • 最后分三个模块输出结果,每个内容的归属都有明确标记,一眼就能看明白差异

你直接把这段代码复制到终端运行,替换file1和file2为你的实际文件名就行,亲测适配你给出的示例内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:42:45