Unix command to find lines common in two files

前端 未结 11 1275
忘掉有多难
忘掉有多难 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:45

    To complement the Perl one-liner, here's its awk equivalent:

    awk 'NR==FNR{arr[$0];next} $0 in arr' file1 file2
    

    This will read all lines from file1 into the array arr[], and then check for each line in file2 if it already exists within the array (i.e. file1). The lines that are found will be printed in the order in which they appear in file2. Note that the comparison in arr uses the entire line from file2 as index to the array, so it will only report exact matches on entire lines.

提交回复
热议问题