Previous post:

Next post:

Compare Two Files Using Comm

by Ramesh

Comm command is used to compare two sorted files line by line.

syntax: comm [OPTION]... FILE1 FILE2

This command will display the lines unique in file1, lines unique in file2, and lines common to both file1 and file2 as shown below.

In the below example,

  • First column displays the lines unique in file1 ( i.e name_list.txt )
  • Second column displays the lines unique in file2 ( i.e name_list_new.txt )
  • Third column displays the lines that are common in both the files.
$ cat name_list.txt

Bram Moolenaar
Ken Thompson
Linus Torvalds

$ cat name_list_new.txt

Bram Moolenaar
Dennis Ritchie
Richard Stallman

$ comm name_list.txt name_list_new.txt
			Bram Moolenaar
		Dennis Ritchie
	Ken Thompson
	Linus Torvalds
		Richard Stallman
Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Previous post:

Next post:

{ 1 comment… read it below or add one }

1 George Morrison January 14, 2010 at 3:00 pm

The real power of comm comes with the OPTIONS not explained above. The comm command can exclude columns of the output using -1, -2, or -3 where the numbers correspond to the columns described above. So to see only the lines that are in file1 but not in file2, you would run comm -23 file1 file2. Similarly to see only the lines that are in file2 but not file1, run comm -13 file1 file2. And finally, to see only the files common to both files, run comm -12 file1 file2.

Leave a Comment

Previous post:

Next post: