How to Use the diff Command to Compare Two Text Files Line by Line in Linux

When managing configuration files or reviewing code in Linux, you often need to figure out exactly what changed between an old version of a file and a new version. Manually reading both files side-by-side to spot a single missing semicolon is virtually impossible. Instead, you can use the built-in diff command to instantly highlight the exact lines that differ between two text files.

How the diff Command Works

The diff command reads two files sequentially and outputs the precise instructions needed to transform the first file into the exact identical structure of the second file. It points out what was added, what was deleted, and what was modified.

To use it, open your terminal and type diff followed by the names of the two files you want to compare:

diff file1.txt file2.txt

Understanding the Output

The output of the standard diff command can look confusing at first glance because it uses cryptic symbols to indicate changes.

  • < (Left Angle Bracket): This indicates a line that exists in the first file but is missing from the second file (a deletion).
  • > (Right Angle Bracket): This indicates a line that exists in the second file but is missing from the first file (an addition).
  • Alphanumeric Codes (e.g., 3c3 or 5a6,7): These codes tell you the line numbers and the action taken. The letter ‘a’ stands for Add, ‘c’ stands for Change, and ‘d’ stands for Delete. For example, 3c3 means “Line 3 in the first file was changed to become Line 3 in the second file.”

How to View the Comparison Side-by-Side

If you find the standard output difficult to read, you can force the diff command to display the files visually side-by-side by adding the -y (yes) flag.

diff -y file1.txt file2.txt

This will split your terminal horizontally. file1.txt will be printed on the left, and file2.txt will be printed on the right. In the middle column between the two files, you will see specific symbols:

  • A | (Pipe symbol) means the line was modified.
  • A < (Less than) means the line was deleted from the first file.
  • A > (Greater than) means the line was added to the second file.

If a line is completely identical in both files, the middle column will be left completely blank, allowing you to instantly scroll down and spot the specific differences.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.