WCC logo

CIS120Linux Fundementals

comm, diff and patch Commands

comm Command

The comm command is used to compare two sorted files line by line. It outputs three columns:

  1. Lines unique to the first file.
  2. Lines unique to the second file.
  3. Lines common to both files.

Syntax:

comm [OPTION]... FILE1 FILE2

Common Options:

Option Description
-1 Suppress column 1 (lines unique to FILE1)
-2 Suppress column 2 (lines unique to FILE2)
-3 Suppress column 3 (lines common to both files)

Example:

file1.txt:

apple
banana
cherry

file2.txt:

banana
cherry
date

Command:

comm file1.txt file2.txt

Output:

apple
        banana
        cherry
                date

diff Command

The diff command is used to compare files line by line. It shows the differences between two files.

Syntax:

diff [OPTION]... FILES

Common Options:

Option Description
-u Output in unified format
-c Output in context format
-i Ignore case differences
-w Ignore all white space

Example with -c option:

file1.txt:

apple
banana
cherry

file2.txt:

banana
cherry
date

Command:

diff -c file1.txt file2.txt

Output:

*** file1.txt 2024-07-11 10:00:00.000000000 +0000
--- file2.txt 2024-07-11 10:00:00.000000000 +0000
***************
*** 1,3 ****
  apple
  banana
  cherry
--- 1,3 ----
  banana
  cherry
  date

Here's how to interpret it the results shown above:

Change Context

Content Changes

Key Observations

  1. Line Removed:
    The line apple from file1.txt is removed in file2.txt.

  2. Line Added:
    The line date is added in file2.txt.

Using diff to create a patch file

You can also create a patch file (to be used later with the patch command) using diff

diff file1 file2 > patchfile

patch Command

The patch command is used to apply changes to a file. It takes a diff file created by the diff command and applies those changes to the original file.

Syntax:

patch [OPTION]... [ORIGFILE [PATCHFILE]]

Common Options:

Option Description
-pNUM Strip NUM leading components from file names
-R Reverse the effect of the patch
-i Read patch from file
-o Output to specified file

Example using diff.patch:

file1.txt:

apple
banana
cherry

diff.patch:

1d0
< apple
3a3
> date

Command:

patch file1.txt diff.patch

Output (file1.txt after patch):

banana
cherry
date

These commands are very useful for file comparison and manipulation tasks in Linux environments, especially when dealing with text files and source code.