diff is an acronym for the difference. It is a useful command used to compare the differences between files based on the lines of the file.
This command just tells us which line to change in the file to make the 2 files the same. To be more precise, it creates a list of changes in the first file to match the second file.
Here at LinuxAPT, as part of our Server Management Services, we regularly help our Customers to perform related Linux system commands queries.
In this context, we shall look into how to compare two text files by the diff command in Linux.
It is given below:
$ diff [options] file1 file2
Here, You need to remember some special symbols of diff:
For example, consider two files, file1.txt and file2.txt.
If file1.txt contains the following four lines of text ($ cat file1.txt ):
Vietnam
England
Japan
China
America
and file2.txt contains these four lines ($ cat file2.txt ):
Malaysia
Campuchia
Vietnam
England
Agentina
Then we can use diff to automatically display for us which lines differ between the two files with this command:
diff file1.txt file2.txt
And the output will be:
0a1,2
> Malaysia
> Campuchia
3,5c5
< Japan
< China
< America
---
> Agentina
Note: This command will print out:
Definition:
1. -c (context): Provides context to easily spot the differences
We will apply with files a.txt and b.txt:
$ diff -c a.txt b.txt
From the output,
*** to specify the first file
— to specify the second file
+ to specify lines that need to add to the first file
! to specify lines that changed
2. -u (unified): To check differences in unified mode:
$ diff -u a.txt b.txt
From the output:
— to specify the first file
+++ to specify the second file
@@ mark the beginning of changes and which line of each file
3. -i: To case sensitive
For example, I have 2 files a.txt and b.txt
$ cat a.txt
FLOWER
chair
$ cat b.txt
flower
table
Now we will try to use the diff command with -i option with these 2 files:
$ diff -i a.txt b.txt
4. –version: Check your version:
$ diff --version
This article covers how to compare two text files by the diff command in Linux. In fact, diff command is used to display the differences in the files by comparing the files line by line. It tells us which lines in one file have is to be changed to make the two files identical.