Linux diff Command: File Comparing

LinuxLinuxBeginner
Practice Now

Introduction

This tutorial provides an introduction to the diff command in Linux, a utility that compares and displays the differences between two text files.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/VersionControlandTextEditorsGroup(["`Version Control and Text Editors`"]) linux(("`Linux`")) -.-> linux/FileandDirectoryManagementGroup(["`File and Directory Management`"]) linux/VersionControlandTextEditorsGroup -.-> linux/diff("`File Comparing`") linux/FileandDirectoryManagementGroup -.-> linux/cd("`Directory Changing`") subgraph Lab Skills linux/diff -.-> lab-219189{{"`Linux diff Command: File Comparing`"}} linux/cd -.-> lab-219189{{"`Linux diff Command: File Comparing`"}} end

diff Command

The diff command is a powerful tool for comparing the contents of two text files and highlighting the differences between them.

Command Usage

Let's begin by understanding the basic usage of the diff command. The diff command is used to compare two text files and display the lines that differ. And first, by using cd /home/labex/project, we change to the specified path /home/labex/project.

terminal

Input:

cd /home/labex/project
diff file1.txt file2.txt

Output:

1,2c1,2
< This is file1.
< It has some content.
---
> This is file2.
> It has different content.
4c4
< Line 4.
---
> New Line 4.

In this example, the diff command compares file1.txt and file2.txt and indicates the differing lines.

Parameters and Usage Examples

The diff command provides options to customize the output and focus on specific aspects of the differences.

Option Parameter

diff [option] file

  • -u: Unified mode to display different contents of files in a consolidated manner.
  • -w: Ignores whitespace differences when comparing files.

Example Usage

1. Unified Format with Context (-u)

This example uses the unified format (-u) and provides context around the differing lines.

Input:

diff -u file1.txt file2.txt

Output:

--- file1.txt	2023-12-27 17:30:47.853086604 +0800
+++ file2.txt	2023-12-27 17:30:47.857086735 +0800
@@ -1,4 +1,4 @@
-This is file1.
-It has some content.
+This is file2.
+It has different content.
 Line 3.
-Line 4.
+New Line 4.

2. Ignore Whitespace Differences (-w)

This example ignores whitespace changes (-w) when comparing file1.txt and file2.txt.

Input:

diff -w file1.txt file2.txt

Output:

1,2c1,2
< This is file1.
< It has some content.
---
> This is file2.
> It has different content.
4c4
< Line 4.
---
> New Line 4.

Summary

The diff command is a valuable tool for comparing text files and identifying differences between them. Whether you need a unified format, want to ignore whitespace changes, or prefer a side-by-side comparison, the diff command provides flexibility for analyzing file discrepancies.

Other Linux Tutorials you may like