How to Compare Two Sorted Files Line by Line Using the comm Command in Linux

When you are managing large text files on a Linux server—such as two lists containing thousands of employee email addresses or server IP addresses—you often need to find the exact overlap between them. Finding out which employees are present in both list_A.txt and list_B.txt is nearly impossible to do manually. While the standard diff command highlights differences, the highly specialized comm (compare) command is specifically designed to isolate and output the common lines shared between two sorted files.

The Prerequisites: Sorting the Files

The comm command operates using a very strict, highly optimized algorithm that reads files line by line. It completely breaks and returns erroneous results if the files are out of alphabetical order. Before you can compare anything, you must guarantee that both files are perfectly sorted.

  1. Sort the first file and save the output:
    sort list_A.txt > sorted_A.txt
  2. Sort the second file and save the output:
    sort list_B.txt > sorted_B.txt

You are now ready to run the comparison.

How to Read the Standard Output

To execute the basic comparison, open your terminal and run:

comm sorted_A.txt sorted_B.txt

The terminal will instantly output a massive wall of text, divided into three distinct, tab-separated columns.

  • Column 1: Lines that exist only in the first file (sorted_A).
  • Column 2: Lines that exist only in the second file (sorted_B).
  • Column 3: Lines that exist in both files (the common overlap).

Filtering the Output with Suppression Flags

The three-column output is visually messy and very difficult to use in a bash script. The true power of the comm command lies in its ability to suppress (hide) specific columns using the -1, -2, and -3 flags.

For example, if you only want to see the email addresses that exist in both files (Column 3), you must instruct the command to suppress Column 1 and suppress Column 2.

comm -12 sorted_A.txt sorted_B.txt

This outputs a clean, single-column list of every identical match.

Conversely, if you are performing an audit and want to find every email address that was present in the first list but is mysteriously missing from the second list, you want to isolate Column 1. To do this, suppress Column 2 and Column 3:

comm -23 sorted_A.txt sorted_B.txt

By combining these suppression flags, you can instantly run complex data audits on massive lists using just a few keystrokes in the terminal.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.