Tips & Tricks: Comparing Text Files in Unix with DIFF command

When working in a unix environment you may find the need to compare the contents of 2 files. To do this unix provides the diff command. The diff command takes 2 files as an argument and outputs the differences between them in a simple easy to understand format using a simple change notation using numbers and the c d a and , characters.

How to run the diff command

Running the diff command is done by typing diff followed by the 2 files to be compared.

diff file1.txt file2.txt
diff file1.txt updates/file2.txt

Understand the output

The diff command outputs the difference found in the file or nothing if there are no differences. The basic syntax is that a reference line will be outputted dictating the lines affected and the type of change followed by the contents of the files for the differing lines.
The type of change is coded by the character between the line references. Where:

  • c: item changed
  • d: item was deleted
  • a: item was added

To the left of the code character is denoted the line numbers present in the first file and to the right is the line numbers in the second file. For example

  • 1c1
    Means the first line differs between the two files
  • 8d7
    Means that line 8 of file one was deleted from file 2 and it would have been present after line 7
  • 9a9
    Means that line 9 of file two was added and would be present after line 9 in file one
  • 2,4c3,5
    Means that there was a multi-line change where lines 2-4 in the first file where changed to the value in lines 3-5 of the second file.

In addition to the codes that explain the differences the lines that are different are also outputted and follow the codes. A < character before teh output means first file and > character means second file. When output is shown for both files in the case of a change — will separate the output of their content. For example

< bbb
< ccc
< ddd
> bcd
> cde
> def
// Tips & Tricks // Unix //

Comments & Questions

Add Your Comment