Comparing Files
In this section, we look at four related topics that involve comparing files:
Checking whether two files are the same, and if not, finding how they differ
Applying the differences between two files to recover one from the other
Using checksums to find identical files
Using digital signatures for file verification
The cmp and diff Utilities
A problem that frequently arises in text processing is determining whether the contents of two or more files are the same, even if their names differ.
If you have just two candidates, then the file comparison utility, cmp, readily provides the answer:
$cp /bin/ls /tmpMake a private copy of /bin/ls $cmp /bin/ls /tmp/lsCompare the original with the copy No output means that the files are identical $cmp /bin/cp /bin/lsCompare different files /bin/cp /bin/ls differ: char 27, line 1 Output identifies the location of the first difference
cmp is silent when its two
argument files are identical. If you are interested only in its exit
status, you can suppress the warning message with the
-s option:
$cmp -s /bin/cp /bin/lsCompare different files silently $echo $?Display the exit code 1 Nonzero value means that the files differ
If you want to know the differences between two similar files, diff does the job:
$echo Test 1 > test.1Create first test file $echo Test 2 > test.2Create second test file $diff test.[12]Compare the two files 1c1 < Test 1 --- > Test 2
It is conventional in using diff to supply the older file as the first argument. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access