Skip to content

comm Command in Linux

Summary

The comm command is used to compare 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 files.

Introduction

The comm command provides a simple yet powerful way to identify differences and similarities between two text files. It's essential that the input files are sorted before using comm, as it relies on the sorted order for accurate comparison. The output is organized into three columns, representing lines unique to the first file, lines unique to the second file, and lines present in both files.

Use case and Examples

Basic Comparison

comm file1.txt file2.txt
This command compares file1.txt and file2.txt. The first column shows lines unique to file1.txt, the second column shows lines unique to file2.txt, and the third column shows lines common to both files.

Suppressing Columns

comm -13 file1.txt file2.txt
This command suppresses the first and third columns. Only lines unique to file2.txt will be displayed.

Identifying Common Lines

comm -12 file1.txt file2.txt
This command suppresses the first and second columns, displaying only the lines that are present in both file1.txt and file2.txt.

Comparing Unsorted Files After Sorting

sort file1.txt > file1_sorted.txt
sort file2.txt > file2_sorted.txt
comm file1_sorted.txt file2_sorted.txt
This set of commands first sorts file1.txt and file2.txt and saves them as file1_sorted.txt and file2_sorted.txt respectively. Then, it uses comm to compare the sorted files.

Commonly used flags

Flag Description Example
-1 Suppress column 1 (lines unique to the first file). comm -1 file1.txt file2.txt
-2 Suppress column 2 (lines unique to the second file). comm -2 file1.txt file2.txt
-3 Suppress column 3 (lines common to both files). comm -3 file1.txt file2.txt
-12 Suppress columns 1 and 2 (show only common lines). comm -12 file1.txt file2.txt
-13 Suppress columns 1 and 3 (show only lines unique to the second file). comm -13 file1.txt file2.txt
-23 Suppress columns 2 and 3 (show only lines unique to the first file). comm -23 file1.txt file2.txt


Share on Share on

Comments