Linux comm Command: Compare Two Sorted Files

comm compares two sorted files line by line. It displays lines unique to the first file, lines unique to the second file, and lines common to both in three columns.

By default, tabs distinguish the second and third columns. Use -1, -2, or -3 to hide the corresponding column. If you need to see changes by line position, diff is more suitable.

Basic syntax

comm [options] sorted_file1 sorted_file2

Implementations and options may vary by distribution. Check your system's documentation with man comm.

Examples

Viewing three types of lines

Compare after sorting both files by the same criteria.

comm old.sorted new.sorted

Display only common lines

Hide the first and second columns, leaving only the third common column.

comm -12 old.sorted new.sorted

Rows only in the second file

Hide columns common with the first file.

comm -13 old.sorted new.sorted

Reading the three columns and common lines

comm distinguishes rows by column that exists only in the first file, the second file, and the row common to both files. -12 hides the first two columns, leaving only the common row.

printf 'apple\nbanana\n' > first.txt
printf 'banana\ncherry\n' > second.txt
comm -12 first.txt second.txt

Example output:

banana

Both files must be pre-sorted within the same locale. Unsorted input makes it difficult to trust the meaning of the columns. Remember that comm compares the presence of rows, and diff shows changes including row positions.

Main Options and Format

Options/Format Description
-1 Hide columns of rows only in the first file.
-2 Hide columns of rows only in the second file.
-3 Hide columns of rows common to both files.
--check-order Check the sort order in the GNU implementation.

Precautions when using

Sort both input files using the same locale. For example, files sorted with LC_ALL=C sort should also be compared under the C locale. Because comm compares sorted lines rather than set membership, decide how duplicate lines should be interpreted before comparing them.

Frequently Asked Questions

What do the columns in the comm result mean?

The first column contains lines only in file1, the second column contains lines only in file2, and the third column contains lines common to both files.

Official Documentation

For exact option behavior, see the GNU Coreutils manual.