Now for something "diff"erent.

dos2unix

Well-Known Member
Joined
May 3, 2019
Messages
3,061
Reaction score
2,789
Credits
26,640

Using the diff Command in Linux to Show Differences in Text Files​

The diff command in Linux is a powerful tool for comparing the contents of two files line by line. It helps you identify differences and can be particularly useful for developers, system administrators, and anyone who works with text files. In this article, we'll explore how to use the diff command and provide some examples to illustrate its functionality.

Basic Usage​

The basic syntax of the diff command is:

diff [options] file1 file2

Here, file1 and file2 are the files you want to compare. By default, diff outputs the differences between the files in a format that shows which lines need to be changed to make the files identical.

Example 1: Comparing Two Files​

Let's say we have two text files, file1.txt and file2.txt, with the following contents:

file1.txt:

Hello, world!
This is a sample file.
It contains some text.

file2.txt:

Hello, world!
This is a sample file.
It contains different text.

To compare these files, you would use the following command:

diff file1.txt file2.txt

The output will look like this:

3c3
< It contains some text.
---
It contains different text.

This output indicates that line 3 in file1.txt ("It contains some text.") is different from line 3 in file2.txt ("It contains different text.").

Example 2: Ignoring Case Differences​

You can use the -i option to ignore case differences when comparing files. For example:

file3.txt:

Hello, World!
This is a Sample File.
It contains some text.

file4.txt:

hello, world!
this is a sample file.
it contains some text.

To compare these files while ignoring case differences, use the following command:

diff -i file3.txt file4.txt

The output will be empty, indicating that there are no differences when case is ignored.

Example 3: Showing Side-by-Side Comparison​

The -y option allows you to display the differences side by side. For example:

diff -y file1.txt file2.txt

The output will look like this:

Hello, world! Hello, world!
This is a sample file. This is a sample file.
It contains some text. | It contains different text.

The | symbol indicates the line that differs between the two files.

Conclusion​

The diff command is a versatile tool for comparing text files in Linux. By understanding its basic usage and options, you can efficiently identify differences between files and manage your text data more effectively.
 
Last edited:


You can use echo $? right away after running diff, or any other command for that matter, to show the exit code. diff will show a different exit code if the files differ.

Signed,

Matthew Campbell
 

Members online


Latest posts

Top