Chapter 11. Comparing Files

Checking Differences with diff

Go to http://examples.oreilly.com/upt3 for more information on: diff

The diff command displays different versions of lines that are found when comparing two files. It prints a message that uses ed-like notation (a for append, c for change, and d for delete) to describe how a set of lines has changed. The lines themselves follow this output. The < character precedes lines from the first file and > precedes lines from the second file.

Let’s create an example to explain the output produced by diff. Look at the contents of three sample files:

test1

test2

test3

apples

apples

oranges

oranges

oranges

walnuts

walnuts

grapes

chestnuts

When you run diff on test1 and test2, the following output is produced:

$ diff test1 test2
3c3
< walnuts
--
> grapes

The diff command displays the only line that differs between the two files. To understand the report, remember that diff is prescriptive, describing what changes need to be made to the first file to make it the same as the second file. This report specifies that only the third line is affected, exchanging walnuts for grapes. This is more apparent if you use the -e option, which produces an editing script that can be submitted to ed , the Unix line editor. (You must redirect standard output (Section 43.1) to capture this script in a file.)

$ diff -e test1 test2
3c
grapes
.

This script, ...

Get Unix Power Tools, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.