The Wayback Machine - https://web.archive.org/web/20240821112222/https://www.geeksforgeeks.org/diff-command-linux-examples/
Open In App

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

Last Updated : 12 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In the world of Linux, managing and comparing files is a common task for system administrators and developers alike. The ability to compare files line by line is crucial for identifying differences, debugging code, and ensuring the integrity of data. One powerful tool that facilitates this process is the diff command. In this article, we will explore how to use the diff command to compare files line by line in Linux.

Understanding the diff Command

diff stands for difference .The diff command is a versatile utility that is pre-installed on most Linux distributions. Its primary purpose is to compare the contents of two files and display the differences between them. The command provides a comprehensive way to highlight changes, additions, and deletions in a clear and readable format.

This command is used to display the differences in the files by comparing the files line by line. Unlike its fellow members, cmp and comm, it tells us which lines in one file have is to be changed to make the two files identical. 

The important thing to remember is that diff uses certain special symbols and instructions that are required to make two files identical. It tells you the instructions on how to change the first file to make it match the second file. 

Basic Syntax of diff Command

The basic syntax of the diff command is as follows:

diff [OPTION]... FILE1 FILE2

Here, `FILE1` and `FILE2` are the two files you want to compare.

The `OPTION` flag allows you to customize the behavior of the `diff` command.

Options Available in diff Command

Option

Description

-c or --context

Output differences in context mode

-u or --unified

Output differences in unified mode (more concise)

-i or --ignore-case

Perform a case-insensitive comparison

–ignore-all-space

Ignore whitespace when comparing lines

–brief

Output only whether files differ, no details

–recursive

Recursively compare directories

-y or --side-by-side

Display the output in a side-by-side format

Pratical Implementaion of How to compare files line by line in Linux? :

Comparing Two Files

Compare files line by line in Linux.

Lets say we have two files with names a.txt and b.txt containing 5 Indian states.  

cat a.txt
cat b.txt
displaying content of files using cat command

displaying content of files using cat command

Now, applying diff command without any option we get the following output:

diff a.txt b.txt
comparing file line by line in linux

comparing file line by line in linux

Let’s take a look at what this output means. The first line of the diff output will contain:  

  • Line numbers corresponding to the first file,
  • A special symbol and
  • Line numbers corresponding to the second file.

Like in our case, 0a1 which means after lines 0(at the very beginning of file) you have to add Tamil Nadu to match the second file line number 1. It then tells us what those lines are in each file preceded by the symbol:  

  • Lines preceded by a < are lines from the first file.
  • Lines preceded by > are lines from the second file.
  • Next line contains 2,3c3 which means from line 2 to line 3 in the first file needs to be changed to match line number 3 in the second file. It then tells us those lines with the above symbols.
  • The three dashes (“—“) merely separate the lines of file 1 and file 2.

As a summary to make both the files identical, first add Tamil Nadu in the first file at very beginning to match line 1 of second file after that change line 2 and 3 of first file i.e. Uttar Pradesh and Kolkata with line 3 of second file i.e. Andhra Pradesh. After that change line 5 of first file i.e. Jammu and Kashmir with line 5 of second file i.e. Uttar Pradesh. 

Deleting a Line in Files using diff Command

Consider the scenario where diff indicates the need to delete a line. Given two files, a.txt and b.txt:

displaying content of files using cat command

displaying content of files using cat command

diff a.txt b.txt
Deleting a Line in File

Deleting a Line in File

Here above output 3d2 means delete line 3rd of first file i.e. Telangana so that both the files sync up at line 2. 

Viewing Differences in Context Mode

To view differences in context mode, use the -c option. Lets try to understand this with example, we have two files file1.txt and file2.txt: 

displaying content of files using cat command

displaying content of files using cat command

diff -c file1.txt file2.txt
Viewing difference in context mode

Viewing difference in context mode

In the above output:

  • The first file is denoted by `***`, and the second file is denoted by `---`.
  • The line with `***************` serves as a separator.
  • The first two lines provide information about file 1 and file 2, displaying the file name, modification date, and modification time.
  • Following that, three asterisks `***` are followed by a line range from the first file (lines 1 through 4). Four asterisks `****` come next. The contents of the first file are then displayed with specific indicators:
    • If a line is unchanged, it is prefixed by two spaces.
    • If a line needs to be changed, it is prefixed by a symbol and a space. The symbols indicate:
      • `+`: A line in the second file to be added to the first file for identical results.
      • `-`: A line in the first file to be deleted for identical results.
  • Three dashes `---` are followed by a line range from the second file (lines 1 through 4), separated by a comma. Four dashes `----` follow, and the contents of the second file are displayed.

Viewing Differences in Unified Mode

To view differences in unified mode, use the -u option. It is similar to context mode but it doesn’t display any redundant information or it shows the information in concise form. 

displaying content of files using cat command

displaying content of files using cat command

diff -u file1.txt file2.txt  
Viewing difference in Unified mode

Viewing difference in Unified mode

In the above output:

  • The first file is indicated by `---`, and the second file is indicated by `+++`.
  • The first two lines provide information about file 1 and file 2, including the modification date and time.
  • After that, `@@ -1`,`4 +1`,`4 @@` denotes the line range for both files. In this case, it represents lines 1 through 4 in both files.
  • The subsequent lines represent the contents of the files with specific indicators:
    • Unchanged lines are displayed without any prefix.
    • Lines in the first file to be deleted are prefixed with -.
    • Lines in the second file to be added are prefixed with +.

In this example, the output indicates that to make both files identical, the lines containing “mv” and “comm” need to be deleted from the first file (file1.txt), and the lines containing “diff” and “comm” need to be added to it.

Case-Insensitive Comparing between Files

By default, `diff` is case-sensitive. To perform a case-insensitive comparison, use the `-i` option:

displaying content of files using cat command

displaying content of files using cat command

The diff command is then used to compare these files with the -i option, which makes the comparison case-insensitive.

diff -i file1.txt file2.txt
case-insensitive Comparing

case-insensitive Comparing

  • 2d1: This indicates a change in line 2 of the first file (file1.txt). The d stands for delete, and it says to delete line 2 from the first file.
    • < mv: This line signifies the content of the line to be deleted. In this case, it is “mv.”
  • 3a3: This indicates an addition in line 3 of the first file (file1.txt). The a stands for add, and it says to add a line at position 3.
    • > diff: This line represents the content to be added. In this case, it is “diff.”

In summary, the output tells us that to make both files identical (ignoring case), we need to delete the line containing “mv” from the first file (file1.txt) and add the line “diff” at the same position. The diff command, with the -i option, allows for a case-insensitive comparison, making it consider “mv” and “MV” as the same during the analysis.

Displaying diff Version

To check the version of `diff` installed on your system, use the `--version` option:

diff --version

Displaying version of diff command

Displaying version of diff command

This command provides information about the version, licensing, and authors of the `diff` utility.

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

How do I use the diff command to compare two files line by line in Linux?

To compare two files line by line using the diff command, simply use the following syntax:

diff file1.txt file2.txt

This command will display the differences between the two files, highlighting additions, deletions, and modifications.

Can I ignore whitespace differences while comparing files with the diff command?

Yes, the diff command provides the -w or --ignore-all-space option to ignore whitespace differences. For example:

diff -w file1.txt file2.txt

This is particularly useful when comparing code files where changes in indentation or spacing are not significant.

How can I create a patch file using the diff command?

To create a patch file representing the differences between two files, use the -u option and redirect the output to a file:

diff -u file1.txt file2.txt > mypatch.patch

The generated patch file can be applied later to synchronize another file with the changes.

What is the unified format in diff output, and how is it different from the context format?

The unified format (`-u` option) in `diff` output provides a more concise and readable representation of differences compared to the context format (`-c` option). It displays changes in a more compact form, making it easier to understand modifications between files.

How do I recursively compare two directories in Linux using the diff command?

To recursively compare two directories and their contents, use the `-r` or `--recursive` option with the diff command:

diff -r directory1/ directory2/

This command compares all files in the specified directories and provides detailed information about the differences.

Conclusion

In the Linux world, comparing files is a common task for system administrators and developers. The `diff command is a handy tool that helps in this process. This article explores how to use `diff` to compare files line by line in Linux. It covers the basic syntax, important options like context mode and unified mode, and practical applications such as creating patch files and recursively comparing directories. Whether you’re debugging code or ensuring file integrity, understanding and mastering the `diff` command is essential for efficient file management in Linux.

 



Previous Article
Next Article

Similar Reads

How to expand/collapse a diff sections in Vimdiff in Linux
Vimdiff is a powerful text editor Linux users love comparing and merging files. It's based on another popular editor called Vim. With Vimdiff, you can easily see the differences between two files side by side. Sometimes, when you're working with big and complicated files, it can be hard to understand all the changes. That's where Vimdiff's expand a
3 min read
Important Linux Commands (leave, diff, cal, ncal, locate and ln)
Linux provides some important tricks. Here are a few and important one's: leave — remind you when you have to leave Syntax: leave +hhmm leave waits until the specified time (within the next 12 hours), then reminds you that you have to leave by writing to the TTY that you executed leave on. You are reminded 5 minutes and 1 minute before the actual t
2 min read
10 Best File Comparison and Difference (Diff) Tools in Linux
When programmers or writers work on files they sometimes need to see the differences between two versions of the same file or between two separate files. This process of finding the differences is called "diffing." On Linux systems, there is a command called " diff " that compares files and shows you what has changed. This command displays the diff
7 min read
How to Compare Local and Remote Files in Linux
In this article, we will discuss how to compare or differentiate between local and remote files in Linux. Programmers and writers often want to know the difference between two files or two copies of the same file when writing program files or regular text files. The discrepancy between the contents of two Linux machine files is referred to as a dif
3 min read
Linux - Installing locate Command to Find Files
In this article, we will see how to install locate command to find files in Linux. locate is a command-line interface tool used for finding files by name in Linux systems. This works more efficiently than other commands. It uses one or more databases by updatedb. To check whether locate utility is already installed in your system. Open up your term
2 min read
How to Compress and Extract Files Using the tar Command on Linux
An archive is a special file that contains any number of files inside. It can be restored via special programs, for example, tar.inside. .tar - archive files are usually not compressed..tar.gz - archive file compressed with gzip tool.tar.bz2 - archive file compressed with bzip2 tool Syntax: tar options [archive_name.tar] files_to_archive The tar co
2 min read
How to List Open Files in Linux | lsof Command
In the world of Linux, understanding and managing open files is crucial for system administrators and users alike. The Linux operating system provides a powerful utility called lsof (List Open Files) that allows users to gain insights into the files currently open on their system. In this article, we will delve into the intricacies of the lsof comm
7 min read
How to Securely Copy Files in Linux | scp Command
scp (secure copy) command in Linux system is used to copy file(s) between servers in a secure way. The SCP command or secure copy allows the secure transferring of files between the local host and the remote host or between two remote hosts. It uses the same authentication and security as it is used in the Secure Shell (SSH) protocol. SCP is known
8 min read
How to Copy Files and Directories in Linux | cp Command
In the world of Linux computers, a common and important job is copying files. The key tool for this task is the "cp" command. In this simple guide, we'll explore how to copy a file in Linux, looking at the basic steps, different choices you can make, and giving clear examples. We'll also take a peek behind the scenes to understand how the "cp" comm
8 min read
How to Compress Files in Linux | Tar Command
File compression is a fundamental task in managing and transferring data efficiently on a Linux system. The Tar command, short for Tape Archive, is a powerful tool that allows users to create compressed and archived files. In this comprehensive guide, we will explore the various options and examples of using the Tar command to compress files on a L
11 min read
How to sort lines in text files in Linux | sort Command
SORT command is used to sort a file, arranging the records in a particular order. By default, the sort command sorts file assuming the contents are ASCII. Using options in the sort command can also be used to sort numerically.  SORT command sorts the contents of a text file, line by line.sort is a standard command-line program that prints the lines
7 min read
Ccat – Colorize Cat Command Output command in Linux with Examples
ccat is a command-line tool for Linux and OSX, which is similar to the cat command in Linux. But the difference between cat and ccat is that the ccat shows the content of the file with the syntax highlighted. Currently, ccat supports the following programming languages. JavaScriptJavaRubyPythonGoCJSONInstallation of Ccat First, we are going to see
2 min read
How to Display Command History in Linux | history Command
The command-line interface in Linux provides powerful tools for users, and mastering command history is essential for efficient navigation and retrieval of previously executed commands. The history command is a valuable utility that allows users to view and search through their command history. In this comprehensive guide, we will explore the vario
4 min read
How to Find Difference Between Two Directories Using Diff and Meld Tools
The diff is a straightforward, original Unix command-line utility that displays the differences between two computer files. It compares files line by line, is simple to use, and is preinstalled on the majority, if not all, Linux distributions. How can we determine the differences between two folders in Linux is the query. Here, we're interested in
2 min read
How to Download YouTube Videos in Linux Command Line?
The videos can be downloaded from the online source through the Linux terminal using the youtube-dl tool. youtube-dl is a Python-based small command-line tool that makes it possible to download the videos from Youtube, Facebook, Dailymotion, and few more similar sites. It is written in PyGTK and requires Python interpreter to run this program, it’s
2 min read
Connecting to the Internet Using Command Line in Linux
Many of the times you may use a Linux system that does not have a GUI after install and it needs an internet connection to set up a desktop environment, also you may use Linux servers without a GUI and you need to connect over a wireless network using the command line. Below you will see Steps to connect to a wireless network using the command line
3 min read
Kali Linux - Command Line Essentials
Command-line plays a vital role while working with Kali Linux as most of its tools don't have a Graphical User Interface and if you are performing ethical hacking or penetration testing then most of the time you will have to work with command Line Interface itself. While executing a command in Kali Linux we enter a command on the terminal emulator
3 min read
Deepl - Command Line Language Translator Tool for Linux
Deepl is the best language translator command-line tool that detects the language of input text and translates it into the desired language using advanced machine learning and neural networking algorithms. It is open source and powered by a German tech Company under the MIT license. It supports the following languages English (EN)Italian (IT)Spanis
3 min read
How to Convert PDF to Image in Linux Command Line?
Pdftoppm is a tool that converts PDF document files into .PNG format and many other formats. We can use this tool on Linux to convert the PDF into images. It also provides the features like the cropping image, set resolution, and scale, and many more. Now let's see how to install the pdftoppm Installation of pdftoppm: To install the pdftoppm, we ne
3 min read
Command-Line Tools and Utilities For Network Management in Linux
If you are thinking of becoming a system administrator, or you are already a system admin, then this article is for you. As a system admin, your daily routine will include configuring, maintaining, troubleshooting, monitoring, securing networks, and managing servers within data centers. Network configuration and troubleshooting are some important t
8 min read
How to Install and Use Sysdig from Linux Command Line?
Sysdig is a tool that provides administrators and developers with unparalleled insight into their systems' behavior. The team behind it hopes to enhance system-level monitoring and troubleshooting by providing a centralized, coherent, and granular view of the storage, transmission, network, and memory subsystems, as well as the ability to generate
2 min read
Aria2 - Multi-Protocol Command-Line Download Tool for Linux
Aria2 is an open-source lightweight multi-protocol, multi-server &amp; multi-source command-line utility that is used for downloading files in Windows, Linux, and Mac. Aria2 is used to download a file at a good speed by utilizing your maximum download bandwidth from multiple sources/protocols such as HTTP(S), FTP, SFTP, Bittorrent, and Metalink. Yo
4 min read
How to Create a Text File Using the Command Line in Linux
There are a couple of quick ways to create a text file from the Linux Command Line or Terminal. Some of them have been explained in the following article. 1) touch commandThis is the most standard command to quickly create an empty text file. The command is quite simple to type and makes it quite easier to create several text files at once. The com
6 min read
Optimize and Compress JPEG or PNG Images in Linux Command line
Today there are many GUI tools that compress and optimize the images, which are very useful. But if you are terminal addicted and want to compress and optimize the images in the terminal before uploading to the cloud, then you can do it. There are two tools by using which we can compress and optimize images. These are - jpegoptimOptiPNGjpegoptim jp
4 min read
Top Linux Command Line Tips and Tricks
Linux is a great OS that offers multiple options for simplifying tasks. It has everything you need for working more efficiently, whether a command-line or a GUI. However, many people don't know the Linux command line's short tricks and end up being stuck in complex tasks. An interface (text-based) through which you communicate with your system's OS
5 min read
How to Manage KVM Virtual Environment using Command Line Tools in Linux
KVM, short for Kernel-based Virtual Machine, is a complete virtualization solution for Linux running on x86 hardware (Intel VT or AMD-V). Since version 2.6.20, the mainline Linux kernel has featured KVM, a complete virtualization solution for Linux running on Intel 64 and AMD 64 hardware that is fast and stable for the majority of workloads. It con
8 min read
How to Pass Command Line Arguments to GDB in a Linux Environment?
The GNU Debugger, commonly known as GDB, is a powerful tool used for debugging and analyzing programs in Linux and other Unix-like operating systems. While GDB is commonly used to debug programs, it can also be used to launch programs with specific command line arguments. This article will walk you through the process of passing command line argume
6 min read
Open Google Chrome From The Linux Command Line
Google Chrome is known as the most used and widely popular web browser because of its fast and better performance. In this article we will learn how we can open the Google Chrome application by using the terminal in Linux along with this we will also look at some you should command line switches to help you to start using the Google Chrome browser
6 min read
MySQL in Kali Linux Command Line
Below is a comprehensive MySQL Command Line tutorial for Kali Linux, starting from beginner to advanced levels. MySQL is a popular open-source relational database management system, and Kali Linux is a Debian-based Linux distribution often used for penetration testing and ethical hacking. Make sure you have MySQL installed on your Kali Linux system
10 min read
Uninstall Node.JS Using Linux Command Line
To uninstall Node.js from your Linux system using the command line, you can follow these steps. The specific commands may vary depending on your Linux distribution, so I'll provide instructions for a few common package managers: APT (Debian/Ubuntu), YUM (Red Hat/CentOS), and DNF (Fedora). Check if Node is Already Installed or NotEnter the following
3 min read
three90RightbarBannerImg