Comparing files or directories: diff

You can display the line by line difference between two files with the diff command.

   diff file1 file2

The information given by the command tells you what changes need to be made for file1 and file2 to match. Lines in file1 are identified with a (<) symbol: lines in file2 with a (>) symbol.

Note that the sdiff command can be used visually to compare two text files side by side on the screen.

diff can also be used to compare the contents of two directories:

   diff directory1 directory2

The information given by the command tells you what to do to make the directories match.

If there is no difference between the files or directories being compared, you are returned to the shell prompt.

Example 1

To compare the contents of two files:

   diff email addresses
   2a3,4
   > Jean JRS@pollux.ucs.co
   > Jim  jim@frolix8

This displays a line by line difference between the file email and addresses.

To make these files match you need to add (a) lines 3 and 4 (3,4) of the file addresses (>) after line 2 in the file email.

Here are the contents of files email and addresses used in this example. Line numbers are shown at the beginning of each line to help you follow this example.

email                           addresses
1 John erpl08@ed                1 John erpl08@ed
2 Joe  CZT@cern.ch              2 Joe  CZT@cern.ch
3 Kim  ks@x.co                  3 Jean JRS@pollux.ucs.co
4 Keith keith@festival		4 Jim  jim@frolix8
                                5 Kim  ks@x.co
                                6 Keith keith@festival

Example 2

To compare two files ignoring differences in the case of the letters and blank spaces:

   diff -iw part1 part_one

Lines in the two files that differ only in case and by the number of spaces they contain are considered to be identical.

Example 3

To compare two directories in the current directory:

   diff usability Usability
   Only in Usability: schedule
   diff usability/email Usability/email
   2a3,4
   > Jean JRS@pollux.ucs.co
   > Jim  jim@frolix8

diff reports that the file (or directory) scheduleis unique to the directory Usability.

diff then reports that there are differences between the file email in the directory usability and the file of the same name in the directory Usability.

To make these files match you need to add (a) lines 3 and 4 (3,4) of the file Usability/email (>) after line 2 in the file usability/email.