代码之家  ›  专栏  ›  技术社区  ›  matt wilkie

如何显示公用行(反向差异)?

  •  155
  • matt wilkie  · 技术社区  · 16 年前

    我有一系列的文本文件,我想知道它们的共同点,而不是它们之间不同的行。命令行unix或windows可以。

    福:

    linux-vdso.so.1 =>  (0x00007fffccffe000)
    libvlc.so.2 => /usr/lib/libvlc.so.2 (0x00007f0dc4b0b000)
    libvlccore.so.0 => /usr/lib/libvlccore.so.0 (0x00007f0dc483f000)
    libc.so.6 => /lib/libc.so.6 (0x00007f0dc44cd000)
    

    酒吧:

    libkdeui.so.5 => /usr/lib/libkdeui.so.5 (0x00007f716ae22000)
    libkio.so.5 => /usr/lib/libkio.so.5 (0x00007f716a96d000)
    linux-vdso.so.1 =>  (0x00007fffccffe000)
    

    因此,考虑到上述两个文件,所需实用程序的输出将类似于 file1:line_number, file2:line_number == matching text (只是一个建议,我真的不在乎语法是什么):

    foo:1, bar:3 == linux-vdso.so.1 =>  (0x00007fffccffe000)
    

    谢谢。

    6 回复  |  直到 7 年前
        1
  •  186
  •   mooreds    10 年前

    不,你可以用 comm . 问题的答案是:

    comm -1 -2 file1.sorted file2.sorted 
    # where file1 and file2 are sorted and piped into *.sorted
    

    以下是完整的用法 comm :

    comm [-1] [-2] [-3 ] file1 file2
    -1 Suppress the output column of lines unique to file1.
    -2 Suppress the output column of lines unique to file2.
    -3 Suppress the output column of lines duplicated in file1 and file2. 
    

    另请注意,在使用comm之前对文件进行排序是很重要的,如手册页中所述。

        2
  •  44
  •   Community CDub    8 年前

    在上找到这个答案 a question listed as a duplicate . 我发现grep比comm更易于管理,所以如果您只想使用一组匹配行(例如用于比较csv),只需使用

    grep -F -x -f file1 file2
    

    或简化的fgrep版本

    fgrep -xf file1 file2
    

    另外,您可以使用 file2* 全局查找多个文件的共同行,而不仅仅是两个文件。

    其他一些方便的变化包括

    • -n 用于显示每个匹配行的行号的标志
    • -c 只计算匹配的行数
    • -v 只显示行 在文件2中 不同的 diff )

    使用 comm 速度更快,但这种速度是以必须先对文件进行排序为代价的。作为一个“反向差异”并不是很有用。

        3
  •  33
  •   Community CDub    8 年前

    以前在这里被问过: Unix command to find lines common in two files

    您也可以尝试使用Perl(Credit goes here )

    perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/'  file1 file2
    
        4
  •  16
  •   Greg Mueller    7 年前

    我刚刚从这个线程中学习了comm命令,但是想添加一些额外的内容:如果文件没有排序,并且您不想接触原始文件,则可以通过管道传输sort命令的输出。这将保留原始文件的完整性。在巴什工作,我不能说其他贝壳。

    comm -1 -2 <(sort file1) <(sort file2)
    

    这可以扩展到比较命令输出,而不是文件:

    comm -1 -2 <(ls /dir1 | sort) <(ls /dir2 | sort)
    
        5
  •  5
  •   Gopu    8 年前

    最简单的方法是:

    awk 'NR==FNR{a[$1]++;next} a[$1] ' file1 file2
    

    文件不需要排序。

        6
  •  1
  •   Zivilyn Bane    10 年前

    仅供参考,我为Windows做了一个小工具,它与“grep-f-x-f file1 file2”做的相同(因为我在Windows上没有找到任何与此命令等效的东西)。

    这里是: http://www.nerdzcore.com/?page=commonlines

    用法为“commonlines inputfile1 inputfile2 outputfile”

    源代码也可用(GPL)