【问题标题】:Comparing file and printing the matches and differences比较文件并打印匹配和差异
【发布时间】:2019-06-24 08:04:33
【问题描述】:

我正在尝试比较 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

【问题讨论】:

  • 为什么不使用diffcomm 呢?无需重新发明轮子!!!

标签: file awk comparison


【解决方案1】:

以下内容完全符合要求...(注意“- 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"
}

【讨论】:

  • 感谢分享。它按预期工作。但我用未排序的文件尝试它不起作用。你能帮忙分类吗?
  • @Rivion -- 嗯.... 代码是这样编写的,因为您的示例数据似乎显示文件是“有序的”。回答这个问题的简单方法是说“先在文件上运行sort?”,但这很可能是一个不平凡的问题,因为很难知道文件应该如何排序/排序。列表中的字符可能会被排除在任何一边。或许您可以将您的问题/数据构建成有助于我们了解您正在寻找的内容的方式?
猜你喜欢
  • 2012-10-18
  • 1970-01-01
  • 2014-02-10
  • 2013-06-17
  • 2016-12-24
  • 2012-09-05
  • 2019-05-15
  • 2019-08-03
  • 2017-07-30
相关资源
最近更新 更多