How to Use “diff” Command in Linux


The diff command analyzes line by line and displays a list of changes between two files. As a special case, diff compares a copy of standard input to itself. This article describes “How to use diff command in Linux.

Futures of “diff” Command –

  • Recognize the changes between one version of a file
  • Compare two configuration or program files
  • Create a patch file which can be applied with the Linux / Unix program patch

How does “diff” Command Works

For example, we have two files as file.txt and file1.txt. The data has been inserted into file.txt as shown below –

I need to buy apples.
I need to run the laundry.
I need to wash the dog.
I need to get the car detailed.

file1.txt  contains the data as shown below

I need to buy apples.
I need to do the laundry.
I need to wash the car.
I need to get the dog detailed.

Use the diff command to compare both the files as shown below –

linux@linux:~$ diff /home/linux/Desktop/file.txt /home/linux/Desktop/file1.txt

The above command should give the result as shown below –

linux@linux:~$ diff /home/linux/Desktop/file.txt /home/linux/Desktop/file1.txt
2,4c2,4
< I need to run the laundry.
< I need to wash the dog.
< I need to get the car detailed. --- > I need to do the laundry.
> I need to wash the car.
> I need to get the dog detailed.

The options of the result should be like this –

a -Added the text to file
c -Changes are made in the file
d -Deletion operation is performed
< Lines from the first file
> Lines from the second file

From the output, 2,4c2,4 means “Lines 2 through 4 in the first file needs to be changed in order to match lines 2 through 4 in the second file”

Let’s look at another example, two text files should be like this-

file.txt

I need to go to the store.
I need to buy some apples.
When I get home, I'll wash the dog.

file1.txt

I need to go to the store.
I need to buy some apples.
Oh yeah, I also need to buy grated cheese.
When I get home, I'll wash the dog.

Use the diff command to compare both files. The command should be like this-

$ diff /home/linux/Desktop/file.txt /home/linux/Desktop/file1.txt

The above command should give the result as shown below –

2a3
> Oh yeah, I also need to buy grated cheese.

From the output, 2a3 means “After line 2 in the first file, a line needs to be added: line 3 from the second file”.

Congratulations! Now, you know “How to use diff command in Linux”. We’ll learn more about these types of commands in our next Linux post. Keep reading!

Other Interesting Posts

Advertisements