The Linux diff command analyses a file line by line and gives an output of a list of changes made between two files.
The command diff is short for difference, which in essence gives the differences between two files.
cmp (compare) and
comm commands, diff highlights the specific line that needs to be changed to match the other files.
One thing Linux administrators cannot forget is that diff uses symbols and instructions to make it more effective.
The specific symbols instruct the command to change the file in a particular way to match the second.
Special Symbols in the diff command output:
- a: add
- c: change
- d: delete
Table of Contents
Linux diff Command Syntax
Copydiff [options] File1 File2
Let’s have a look at diff command example usages.
Case 1: Change
Assume we have two files: x.txt and y.txt
x.txt contains the following content.
CopyCalifornia Miami Ohio Kansas Texas
y.txt contains the following content.
CopyCalifornia Nevada Georgia Kansas Texas
Now, use the diff command to make the comparison between the two files as shown.
Copy$ diff x.txt y.txt
Let’s examine the output in more detail.
2,3c2,3 line implies that lines 2 and 3 from the first file need to be changed in order to match lines 2 and 3 from the second text file.
diff Command Output Symbols explained
Let’s briefly look at the various symbols encountered in the output.
- The less than symbol indicates lines from the first line
- The greater than symbol indicates lines from the second line
Copya - Denotes that text was added to the file c - Denotes that changes were made in the file d - Indicates that the line was expunged or deleted
Let’s take a look at another example.
Case 2: Adding
We have two text files:
The file file 1.txt has the following content.
CopyLinux is a great operating system It's free and opensource It's light and stable I would highly recommend it
file2.txt has the following content.
CopyLinux is a great operating system It's free and opensource It's light and stable Oh ! It can be installed on almost any PC hardware I would highly recommend it
Use the diff command to compare both files.
Copy$ diff file1.txt file2.txt
From the output above,
3a4 implies that after line 3 from the first file, another line needs to be added to match line 4 from the second file.
Case 3: Deletion
Consider two files as below.
file3.txt with the following content.
CopyApples Oranges Mangoes Peaches Bananas Grapes
And file4.txt which has the following content.
CopyApples Oranges Mangoes Bananas Grapes
Again, use the diff command to compare both files.
Copy$ diff file3.txt file4.txt
Here the output 4d3 means that delete the 4th line from the first file to sync up with the second file at line number 3.
Linux diff command is a simple utility to compare two files. It’s useful in checking for the changes between two versions of a text file.