Next 16: Programming  Up 15: File Utilities  Prev 15.H: Sorting Files with sort  Contents

Specialized

§ 15.I: Comparing Files with diff and cmp


The diff command is used to compare two text files. To compare the files type the command diff followed by the files you wish to compare. Try comparing sample.doc with vi.doc.
> diff sample.doc vi.doc

If you only changed the name and date without moving any lines your output would look similar to

18c18
< NAME  DATE
---
> Melanie Johnson  10-12-96
The first line indicates the line numbers (or group of line numbers) that differs from the first and second file respectively. The c between the numbers indicates that line 18 (in sample.doc) must be changed to match line 18 (in vi.doc) if the two documents are to match. The lines starting with the symbol < are the lines in the first file. The lines starting with > are the lines in the second file. diff will repeat this grouping until it has finished the file. Try using the diff command again to \ compare the original sample-homepage.html to index.html as a quiz.

Do the changes indicated make sense?

The cmp command is also used to compare two files. Because it gives a yes or no answer, it can be used for binary files. The syntax is cmp followed by the two file names. If the two files are identical it gives no response. If the two files are different it gives the filename and byte of the first difference. For instance, try
> cd public-html/figs
> cp osu.gif osu.bak
> diff osu.gif osu.bak

No response. Now try
> diff osu.gif osugrey.gif

diff responds

  
diff: 0653-827 Missing newline at the end of file osu.gif.  
so the files are different.

One of the great strengths of Unix is its wide variety of powerful file Utilities. What you have seen in this tutorial only begins to scratch the surface. To learn more about file utilities you may wish to consult "Coping With Unix" or another Unix manual. Using man -k to search the man pages for the specific function you wish to perform may also be productive if you can describe it well with one word and some synonyms. As you work with Unix you may find yourself thinking "I wish there was an easy way to ...". If you do a little investigating, you may find that there is a utility that does exactly what you want.


Next 16: Programming  Up 15: File Utilities  Prev 15.H: Sorting Files with sort  Contents

Comments and questions to Dr. Elias N. Houstis at enh@cs.purdue.edu.