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.

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

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

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.