Introduction
This tutorial provides an introduction to the diff
command in Linux, a utility that compares and displays the differences between two text files.
This tutorial provides an introduction to the diff
command in Linux, a utility that compares and displays the differences between two text files.
The diff
command is a powerful tool for comparing the contents of two text files and highlighting the differences between them.
Let's begin by understanding the basic usage of the diff
command. The diff
command is used to compare two text files and display the lines that differ. And first, by using cd /home/labex/project
, we change to the specified path /home/labex/project
.
Input:
cd /home/labex/project
diff file1.txt file2.txt
Output:
1,2c1,2
< This is file1.
< It has some content.
---
> This is file2.
> It has different content.
4c4
< Line 4.
---
> New Line 4.
In this example, the diff
command compares file1.txt
and file2.txt
and indicates the differing lines.
The diff
command provides options to customize the output and focus on specific aspects of the differences.
diff [option] file
-u
: Unified mode to display different contents of files in a consolidated manner.-w
: Ignores whitespace differences when comparing files.This example uses the unified format (-u) and provides context around the differing lines.
Input:
diff -u file1.txt file2.txt
Output:
--- file1.txt 2023-12-27 17:30:47.853086604 +0800
+++ file2.txt 2023-12-27 17:30:47.857086735 +0800
@@ -1,4 +1,4 @@
-This is file1.
-It has some content.
+This is file2.
+It has different content.
Line 3.
-Line 4.
+New Line 4.
This example ignores whitespace changes (-w) when comparing file1.txt and file2.txt.
Input:
diff -w file1.txt file2.txt
Output:
1,2c1,2
< This is file1.
< It has some content.
---
> This is file2.
> It has different content.
4c4
< Line 4.
---
> New Line 4.
The diff
command is a valuable tool for comparing text files and identifying differences between them. Whether you need a unified format, want to ignore whitespace changes, or prefer a side-by-side comparison, the diff
command provides flexibility for analyzing file discrepancies.