Linux / UNIX Display Lines Common in Two Files

Q. I’m trying to use diff command, but it is not working. I’d like to display those lines that are common to file1 and file2? How do I do it?

A. Use comm command; it compare two sorted files line by line. With no options, produce three column output. Column one contains lines unique to FILE1, column two contains lines unique to FILE2, and column three contains lines common to both files.

Advertisement

To Display Those Lines That Are Common to File1 and File2

Type the command as follows:
$ comm /path/to/file1/ /path/to/file2
$ comm -1 /path/to/file1/ /path/to/file2
$ comm -2 /path/to/file1/ /path/to/file2
$ comm -3 /path/to/file1/ /path/to/file2

Where,

  • -1 : suppress lines unique to FILE1
  • -2 : suppress lines unique to FILE2
  • -3 : suppress lines that appear in both files

You can also try out perl code (it was posted by someone at comp.unix.shell news group):

$ perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/'  file1 file2

🥺 Was this helpful? Please add a comment to show your appreciation or feedback.

nixCrat Tux Pixel Penguin
Hi! 🤠
I'm Vivek Gite, and I write about Linux, macOS, Unix, IT, programming, infosec, and open source. Subscribe to my RSS feed or email newsletter for updates.

23 comments… add one
  • Adrien Sep 23, 2013 @ 14:52

    In python :

    import sys,os
    file1 = open(sys.argv[1],"r")
    file2 = open(sys.argv[2],"r")
    
    lines1 = file1.readlines()
    lines2 = file2.readlines()
    print "File %s has %s lines" % (sys.argv[1],len(lines1))
    print "File %s has %s lines" % (sys.argv[2],len(lines2))
    
    found = []
    notfound = []
    for idx,l in enumerate(lines1) :
    	print "Doing line %s in file %s : %s" % (idx,sys.argv[1],l)
    	for idx2,l2 in enumerate(lines2) :
    		if l == l2 :
    			print "Found %s ( ==  %s ) in file %s at index %s" % (l,l2, sys.argv[2],idx2)
    			found.append(l)
    			continue
    			print "Found : %s , Not Found : %s" % (len(found),len(notfound))
    	notfound.append(l)
    	print "Found : %s , Not Found : %s" % (len(found),len(notfound)) 
    

    python nameofthescript.py file1 file2

    You can comment prints of course

  • self Jan 28, 2015 @ 15:47

    1) for i in `cat file1`; do grep –color $i file2; done
    2) grep -f file1 file2

  • Arulraj Feb 2, 2015 @ 14:14

    In a file having following data

    adsdfsf 10 sdfd 10
    sdsgfjf 5 hdvfd 10
    gdyfdfd 20 jdfhd 564

    I want to compare column one with column two. Please any body knows reply to my mail id.

  • rod May 9, 2015 @ 17:46

    i want to do this but with two strings saved in two bash variables… is this possible with comm?

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre> for code samples. Your comment will appear only after approval by the site admin.