首页 > 解决方案 > 比较文件并打印匹配和差异

问题描述

我正在尝试比较 2 个文件并打印如下输出:

F1:

a|b|c|d|e|f|g
q|w|e|r||f|

F2:

a|b|c|d|e|f|g
q|w|e|r|t|f|u

输出:

f1 - a|b|c|d|e|f|g - f2 - a|b|c|d|e|f|g  - All columns are matching
f1 - q|w|e|r||f| - f2 - q|w|e|r|t|f|u - Column 5 and 7 are not matching

标签: fileawkcomparison

解决方案


以下正是所要求的......(注意“- All”之前的两个空格和不匹配的大小写中的一个空格,并且 f1 和 f2 是小写的)。如果我们想使用文件名而不是 f1 和 f2,可以使用 FILENAME 变量

#! /usr/bin/awk -f
BEGIN {
    FS = "|"
    split("", f1)
}

NR == FNR { # this is true only for the first file processed
    f1[FNR] = $0
    next
}

$0 == f1[FNR] { # with the second file, if lines are equal...
    print "f1 - " f1[FNR] " - f2 - " $0 "  - All columns are matching"
    next
}

{ # if the lines are not equal, split and find the columns not equal
    sz = split(f1[FNR], f)
    if (NF > sz)
        sz = NF
    c = ""
    for (i=1; i<=sz; ++i)
            if (f[i] != $i) {
                    c = i++
                    break
            }
    for (; i<=sz; ++i)
            if (f[i] != $i)
                    c = c " and " i
    print "f1 - " f1[FNR] " - f2 - " $0 " - Column " c " are not matching"
}

推荐阅读