Linux comm Command: Common Line Comparison

LinuxLinuxBeginner
Practice Now

Introduction

This tutorial provides an introduction to the comm command in Linux, a utility that compares two sorted files line by line.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/VersionControlandTextEditorsGroup(["`Version Control and Text Editors`"]) linux(("`Linux`")) -.-> linux/FileandDirectoryManagementGroup(["`File and Directory Management`"]) linux/VersionControlandTextEditorsGroup -.-> linux/comm("`Common Line Comparison`") linux/FileandDirectoryManagementGroup -.-> linux/cd("`Directory Changing`") subgraph Lab Skills linux/comm -.-> lab-219186{{"`Linux comm Command: Common Line Comparison`"}} linux/cd -.-> lab-219186{{"`Linux comm Command: Common Line Comparison`"}} end

comm Command

The comm command is a useful tool for comparing two sorted files and displaying the lines that are common, unique to each file, or unique to the combined set.

Command Usage

Let's begin by understanding the basic usage of the comm command. The comm command is used to compare two sorted files line by line. And first, by using cd /home/labex/project, we change to the specified path /home/labex/project. Then, we use the comm command to compare the contents of file1.txt and file2.txt.

terminal

Input:

cd /home/labex/project
comm file1.txt file2.txt

Output:

	Goodbye
Hello
		Labex

In this example, the comm command compares the contents of file1.txt and file2.txt and displays the lines that are common and unique to each file.

Parameters and Usage Examples

The comm command provides options to customize the output and focus on specific types of lines.

Option Parameter

comm [option] file1 file2

  • -1: Do not output the lines unique to file1.
  • -2: Do not output the lines unique to file2.
  • -3: Do not output the lines common to both files.

Example Usage

1. Display Only Common Lines

The comm command can be used to display only the lines that are common between two files. In this example, we will compare two files and show only the common lines:

Input:

comm -12 file1.txt file2.txt

Output:

Labex

2. Display Unique Lines

You can use the comm command to display lines unique to each file. In this example, we will display lines unique to file1.txt:

Input:

comm -23 file1.txt file2.txt

Output:

Hello

Summary

The comm command is a valuable tool for comparing sorted files and analyzing the differences or similarities between their contents. Whether you need to find common lines, unique lines, or suppress specific columns in the output, the comm command provides a flexible and efficient solution.

Other Linux Tutorials you may like