The diff
command in Linux is a powerful tool used to compare files line by line and identify differences between them. It provides a clear and structured output, showing the lines that need to be changed, added, or removed to make the files identical.
Syntax of diff
Command
diff [options] file1 file2
file1
: The first file to compare.file2
: The second file to compare.[options]
: Optional flags to modify the behavior or output format.
Basic Usage of diff
- Compare Two Text Files:
diff file1.txt file2.txt
Output Explanation:
- Lines starting with
<
are fromfile1
. - Lines starting with
>
are fromfile2
. - Contextual indicators (
a
,c
,d
) explain whether lines are added, changed, or deleted.
- Lines starting with
- Side-by-Side Comparison:
diff -y file1.txt file2.txt
This displays the differences side by side:
- The
|
symbol indicates differing lines. <
and>
indicate missing or extra lines in one file.
- The
Options with diff
- Show Context Lines:
diff -c file1.txt file2.txt
Displays several lines of context around the differences for better clarity.
- Unified Output:
diff -u file1.txt file2.txt
Produces a unified format, often used in patches.
- Ignore Whitespace Differences:
diff -w file1.txt file2.txt
Ignores differences in spaces or tabs.
- Suppress Identical Files:
diff -q file1.txt file2.txt
Displays only whether the files differ, without showing the actual differences.
- Limit Output to a Specific Number of Lines:
diff -C 3 file1.txt file2.txt
Displays only 3 lines of context around the differences.
Example
Consider two files:
file1.txt:
apple
banana
cherry
date
file2.txt:
apple
banana
grape
date
Command:
diff file1.txt file2.txt
Output:
3c3
< cherry
---
> grape
Graphical Tools for Comparison
For users who prefer graphical tools, utilities like Meld or KDiff3 provide an intuitive interface for comparing files line by line.
Install Meld:
sudo apt install meld
Launch Meld:
meld file1.txt file2.txt
Conclusion
The diff
command is a versatile tool for comparing files line by line in Linux. Whether you prefer minimalistic output, side-by-side comparison, or graphical interfaces, diff
and its options provide flexibility and precision for file comparison tasks.