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
Subscribe to our free e-mail newsletter or RSS feed to get all updates.
You can Email this page to a friend.
Related Linux / UNIX FAQ:
- Howto: Linux command line utilities for removing blank lines from text files
- How do I Compare two files under Linux or UNIX?
- Delete text or paragraph between two sections using sed
- Shell Script To Number Lines Of Files
- Shell script reverse lines of a file
Discussion on This FAQ
Leave a Reply
We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Please do not use the comment form to ask for help / question. Ask your question on the excellent Linux tech support forum. Thank you very much for stopping by our site!
Tags: comm command, compare two files, display common lines to both files, Linux, Perl, shell, UNIX ~ Last updated on: April 12, 2008



April 14th, 2008 (5 weeks ago) at 7:37 pm
And if you want to find the lines NOT common in 2 files, use diff