How to Compare Files Using diff in Linux

How to Compare Files Using diff in Linux

Hey there! 👋 Welcome to another beginner-friendly Linux tutorial on ProgramGuru.org. Today, we’re learning how to compare files using the diff command.

If you’ve ever had two text files and wanted to know what’s different between them, diff is your new best friend. It's like a side-by-side detective for your text files!

📘 What is diff?

The diff command shows the difference between two files line by line. It tells you what needs to be changed in the first file to make it identical to the second file.

🛠️ Let’s Start with a Simple Example

First, we’ll create two text files. Open your terminal and type:

echo "apple" > file1.txt
echo "banana" >> file1.txt
echo "cherry" >> file1.txt

echo "apple" > file2.txt
echo "blueberry" >> file2.txt
echo "cherry" >> file2.txt

This creates two files with slight differences. Now let’s compare them using diff:

diff file1.txt file2.txt

🖥️ Output:

2c2
< banana
---
> blueberry

Let’s decode this:

  • 2c2: Line 2 in file1 was "changed" to line 2 in file2
  • < means the line in file1.txt
  • > means the line in file2.txt

So the second line changed from “banana” to “blueberry.” Easy, right?

💡 Optional Flags for Better Comparison

You can also use diff with some useful options:

  • -y: Shows side-by-side comparison
  • --suppress-common-lines: Hides lines that are the same
diff -y --suppress-common-lines file1.txt file2.txt

🖥️ Output:

banana          | blueberry

Now it’s even easier to spot what changed!

🔚 Wrapping Up

And that’s it! You’ve just learned how to use diff to compare files in Linux. It’s a powerful tool that’s simple to use and can save you a lot of time when debugging or reviewing changes.

If you’re enjoying these tutorials, don’t forget to subscribe to our channel and keep exploring the world of Linux with us at ProgramGuru.org 💻🚀


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...