Wednesday, January 15, 2025
HomeTechHow to Compare Files Line by Line in Linux | diff Command

How to Compare Files Line by Line in Linux | diff Command

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

  1. Compare Two Text Files:
    diff file1.txt file2.txt
    

    Output Explanation:

    • Lines starting with < are from file1.
    • Lines starting with > are from file2.
    • Contextual indicators (a, c, d) explain whether lines are added, changed, or deleted.
  2. 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.
See also  Read a file line by line in Python

Options with diff

  1. Show Context Lines:
    diff -c file1.txt file2.txt
    

    Displays several lines of context around the differences for better clarity.

  2. Unified Output:
    diff -u file1.txt file2.txt
    

    Produces a unified format, often used in patches.

  3. Ignore Whitespace Differences:
    diff -w file1.txt file2.txt
    

    Ignores differences in spaces or tabs.

  4. Suppress Identical Files:
    diff -q file1.txt file2.txt
    

    Displays only whether the files differ, without showing the actual differences.

  5. 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.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x