【问题标题】:Line number with comm command. Is it possible?带有 comm 命令的行号。可能吗?
【发布时间】:2021-01-06 16:59:36
【问题描述】:

我用这个命令比较两个文件

comm -13 file1 file2

它完美地工作并告诉我不同​​之处。但我还想告诉我行号(第二个文件中唯一的行)。

文件1:

a
d
e
f
g

文件2:

a
b
c
d
e

我愿意:

 comm -13 file1 file2

输出

b
c

但我需要 file2 中 b 和 c 所在的行号,所需的输出:

2
3

【问题讨论】:

    标签: bash awk compare comm


    【解决方案1】:
    awk 'NR==FNR{a[$0]++; next} (--a[$0]) < 0{print FNR}' file1 file2
    

    例如使用包含额外d 行的修改后的file2 来证明重复值得到了正确处理:

    $ cat file2
    a
    b
    c
    d
    d
    e
    

    $ comm -13 file1 file2
    b
    c
    d
    

    $ awk 'NR==FNR{a[$0]++; next} (--a[$0]) < 0' file1 file2
    b
    c
    d
    

    $ awk 'NR==FNR{a[$0]++; next} (--a[$0]) < 0{print FNR}' file1 file2
    2
    3
    5
    

    【讨论】:

      【解决方案2】:

      使用 awk:

      $ awk 'NR==FNR{a[$0];next}!($0 in a){print FNR}' file1  file2
      

      输出:

      2
      3
      

      编辑:如 OP 中所述,当文件 file2 具有重复项时,comm 的行为会有所不同。下面的解决方案应该可以解决这个问题(请参阅 cmets 并感谢@EdMorton):

      $ awk '
      NR==FNR {
          a[$0]++
          next
      }
      {
          if(!($0 in a)||a[$0]<=0)
              print FNR
          else a[$0]--
      }' file1 file2
      

      现在输出(file2 有重复条目 d 其中FNR==5):

      2
      3
      5
      

      希望没有更多的陷阱等待......

      【讨论】:

      • 这不太一样。将第二行 d 添加到文件 a 然后尝试 comm -13 b a 和您的 awk 命令,您会发现前者正确输出 d 而后者不输出与 @ 关联的行号987654334@,因为它不考虑重复。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-29
      • 2011-07-12
      相关资源
      最近更新 更多