How to Use the Linux comm Command to Compare Two Sorted Files

When you have two massive lists of data—such as an inventory list of servers from last week and an updated inventory list from this week—you often need to quickly identify the differences. Which servers were added? Which were decommissioned? Which servers exist in both lists? While the diff command is excellent for comparing complex source code line-by-line, it can be overly verbose for simple lists. For straightforward list comparison, Linux provides the comm command. It reads two sorted text files and outputs a clean, three-column table showing exactly which lines are unique to file one, unique to file two, or common to both.

The Golden Rule: Sorting is Required

The comm command relies on a specific algorithmic assumption to process files rapidly: both input files must be alphabetically or numerically sorted before they are compared. If you feed unsorted files into comm, it will silently fail or produce completely inaccurate results.

If your files are not sorted, you must sort them first using the sort command:

sort old_servers.txt > old_servers_sorted.txt
sort new_servers.txt > new_servers_sorted.txt

Running the comm Command

Once your files are prepared, comparing them is simple.

  1. Open your terminal.
  2. Type the command followed by the two sorted files: comm old_servers_sorted.txt new_servers_sorted.txt
  3. Press Enter.

Understanding the Output Columns

The output will print directly to your screen, indented by Tab characters. It is strictly divided into three columns:

  • Column 1 (Far Left): Lines that are completely unique to the FIRST file you specified. (In our example, these are servers that existed last week but do not exist this week—they were deleted/decommissioned).
  • Column 2 (Middle): Lines that are completely unique to the SECOND file you specified. (These are new servers that were added this week).
  • Column 3 (Far Right): Lines that appear identically in BOTH files. (These are servers that have remained unchanged).

Filtering the Output with Flags

Viewing a massive three-column list is difficult. The true power of comm lies in its suppression flags. You can tell the command to suppress (hide) specific columns by passing their corresponding numbers (1, 2, or 3) as arguments.

  • Show only common lines: To see only the servers that exist in both lists, you must suppress columns 1 and 2. comm -12 old_servers.txt new_servers.txt
  • Show only new lines: To see only the servers that were added this week, you must suppress columns 1 and 3 (leaving only column 2 visible). comm -13 old_servers.txt new_servers.txt
  • Show only deleted lines: To see only the servers that were removed since last week, suppress columns 2 and 3. comm -23 old_servers.txt new_servers.txt

Get the best tech tips delivered straight to your inbox.

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