how to show lines in common (reverse diff)?

前端 未结 7 935
花落未央
花落未央 2020-11-27 10:35

I have a series of text files for which I\'d like to know the lines in common rather than the lines which are different between them. Command line unix or windows is fine.

相关标签:
7条回答
  • 2020-11-27 10:48

    Found this answer on a question listed as a duplicate. I find grep to be more admin-friendly than comm, so if you just want the set of matching lines (useful for comparing CSVs, for instance) simply use

    grep -F -x -f file1 file2
    

    or the simplified fgrep version

    fgrep -xf file1 file2
    

    Plus, you can use file2* to glob and look for lines in common with multiple files, rather than just two.

    Some other handy variations include

    • -n flag to show the line number of each matched line
    • -c to only count the number of lines that match
    • -v to display only the lines in file2 that differ (or use diff).

    Using comm is faster, but that speed comes at the expense of having to sort your files first. It isn't very useful as a 'reverse diff'.

    0 讨论(0)
  • 2020-11-27 10:51

    On *nix, you can use comm. The answer to the question is:

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

    Here's the full usage of 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. 
    

    Also note that it is important to sort the files before using comm, as mentioned in the man pages.

    0 讨论(0)
  • 2020-11-27 10:52

    Just for information, i made a little tool for Windows doing the same thing than "grep -F -x -f file1 file2" (As i haven't found anything equivalent to this command on Windows)

    Here it is : http://www.nerdzcore.com/?page=commonlines

    Usage is "CommonLines inputFile1 inputFile2 outputFile"

    Source code is also available (GPL)

    0 讨论(0)
  • 2020-11-27 10:54

    I just learned the comm command from this thread, but wanted to add something extra: if the files are not sorted, and you don't want to touch the original files, you can pipe the outptut of the sort command. This leaves the original files intact. Works in bash, I can't say about other shells.

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

    This can be extended to compare command output, instead of files:

    comm -1 -2 <(ls /dir1 | sort) <(ls /dir2 | sort)
    
    0 讨论(0)
  • 2020-11-27 10:56

    Was asked here before: Unix command to find lines common in two files

    You could also try with perl (credit goes here)

    perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/'  file1 file2
    
    0 讨论(0)
  • 2020-11-27 11:02

    Easiest way to do is :

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

    Files are not necessary to be sorted.

    0 讨论(0)
提交回复
热议问题