Unix command to find lines common in two files

前端 未结 11 1260
忘掉有多难
忘掉有多难 2020-11-27 10:32

I\'m sure I once found a unix command which could print the common lines from two or more files, does anyone know its name? It was much simpler than diff.

11条回答
  •  余生分开走
    2020-11-27 10:46

    To easily apply the comm command to unsorted files, use Bash's process substitution:

    $ bash --version
    GNU bash, version 3.2.51(1)-release
    Copyright (C) 2007 Free Software Foundation, Inc.
    $ cat > abc
    123
    567
    132
    $ cat > def
    132
    777
    321
    

    So the files abc and def have one line in common, the one with "132". Using comm on unsorted files:

    $ comm abc def
    123
        132
    567
    132
        777
        321
    $ comm -12 abc def # No output! The common line is not found
    $
    

    The last line produced no output, the common line was not discovered.

    Now use comm on sorted files, sorting the files with process substitution:

    $ comm <( sort abc ) <( sort def )
    123
                132
        321
    567
        777
    $ comm -12 <( sort abc ) <( sort def )
    132
    

    Now we got the 132 line!

提交回复
热议问题