comm command in Linux with examples
comm compare two sorted files line by line and write to standard output; the lines that are common and the lines that are unique.
Suppose you have two lists of people and you are asked to find out the names available in one and not in the other, or even those common to both. comm is the command that will help you to achieve this. It requires two sorted files which it compares line by line.
Before discussing anything further first let’s check out the syntax of comm command:
Syntax :
$comm [OPTION]... FILE1 FILE2
- As using comm, we are trying to compare two files therefore the syntax of comm command needs two filenames as arguments.
- With no OPTION used, comm produces three-column output where first column contains lines unique to FILE1 ,second column contains lines unique to FILE2 and third and last column contains lines common to both the files.
- comm command only works right if you are comparing two files which are already sorted.
Example: Let us suppose there are two sorted files file1.txt and file2.txt and now we will use comm command to compare these two.
// displaying contents of file1 // $cat file1.txt Apaar Ayush Rajput Deepak Hemant // displaying contents of file2 // $cat file2.txt Apaar Hemant Lucky Pranjal Thakral
Now, run comm command as:
// using comm command for comparing two files // $comm file1.txt file2.txt Apaar Ayush Rajput Deepak Hemant Lucky Pranjal Thakral
The above output contains of three columns where first column is separated by zero tab and contains names only present in file1.txt ,second column contains names only present in file2.txt and separated by one tab and the third column contains names common to both the files and is separated by two tabs from the beginning of the line.
This is the default pattern of the output produced by comm command when no option is used .