Linux Diff Command Tutorial with Examples To Compare Two Text File


Comparing files line by line can be done with a tool named diff. There are a lot of different options provided by diff. We will look at the most popular and useful features in this tutorial.

Syntax

diff has simple syntax. There are options that we will look later and files to be compared.

diff [OPTION] FILES

Compare Two Files

In this example, we will compare two files line by line

$ diff file1 file2

If there is no output after diff operation this means that there is no difference between files.

In this output, we see that one line is different. > means the second file has one extra line

  • 3a4 means after line 3 line 4 is added

We change file and compare again with the same command

file1

This is line 1 
We can resume 
Extra file 
Change the station

file2

This is line 1 
We can resume 
Change the station 
Forth line
$ diff file1 file2
Compare Two Files
Compare Two Files
  • 3d2 Lines 3 in the file1 need to be deleted in order to match line 2 in the file2
  • 4a4 From file2 delete line 4 to match first file line 4

View Verbose Diff

We can list all lines of two files with which lines will add or deleted both files to match each other.

$ diff -c file1 file2
View Verbose Diff
View Verbose Diff

Unified Mode

In a unified view, only one file is shown with related changes like delete or add. It is simpler than verbose mode to review.

$ diff -u file1 file2
Unified Mode
Unified Mode

LEARN MORE  How To Start, Stop, Restart Networking On Linux?

Leave a Comment