Skip to main content

3.1.5 Comparing Files

To compare two files, the command diff is useful. This command has many different options, which you should investigate more in-depth in your favourite linux book. A simple way to use diff is without options in the following way:

diff file1 file2

Putting it into Practice:

We'll be using the file lines.txt again. First, copy lines.txt to lines2.txt
Then, edit lines2.txt such that line 30 now reads "This is the special line 30". Save and quit out of emacs. So, now lines.txt and lines2.txt differ only by one line, on line 30.
Now compare these two files by typing
 diff lines.txt lines2.txt 
and hitting return
You should get the following output:
< this is line 30
> this is the special line 30

This output is a reversible list of editing instructions for transforming file1 into file2 (in this case, for transforming lines.txt into lines2.txt) .To decipher this output; the first line of output "30c30" tells you to replace line 30 of file1 (lines.txt) with line 30 of file2 (lines2.txt). The next few lines of output show all the lines that would be involved in this editing transformation, with < indicating lines from file1 and > indicating lines from file2

In general, the editing instructions upon output take the following forms:
n1, n2 d n3 This means to delete lines n1 to n2 in file 1
n1 a n3, n4 This means to append lines n3 to n4 of file2 after line n1 of file1
n1, n2 c n3, n4 This means to replace (change) lines n1 to n2 of file1 with lines n3 to n4 of file2

You can do much more with diff - refer to a textbook on linux or the man pages to get an in-depth appreciation of this command.