|
|
It is often necessary to compare the contents of two files and list any differences. This may be because you have made some changes to a file and cannot remember them; if you have a previous version of the file, you can compare the two. You may have two files with the same name in different directories; you can compare them to see if they are different files or two versions of the same file.
To see if two files differ, use the
cmp(C)
(compare) command which reads file1 and file2
and reports whether or not they are different:
cmp file1 file2
If they differ, cmp reports the point at which the two files diverge. This is reported in terms of the number of characters into file1 at which the difference was detected, and the number of the line containing that character, as follows:
$ cmp chapter4 chapter4.bak chapter4 chapter4.bak differ: char 28895, line 849In this case, the two files are the same up to a point on line 849 of chapter4.
To see the precise differences on a line-by-line basis, use the
diff(C)
command, as follows:
diff filename1 filename2
For example, consider the following two files, note.1 and note.2:
$ cat note.1 Charles Please send me a report. I need it for tomorrow's meeting. Thanks Bridget $ cat note.2 Charles Please send me a report today. I need it for tomorrow's meeting. Thank you BridgetTo compare these files, line by line, use the diff command as follows:
$ diff note.1 note.2 2c2 < Please send me a report. --- > Please send me a report today. 4c4 < Thanks --- > Thank youThe ``2c2'' means that there is a change (``c'') between line 2 in the first file and line 2 in the second. Likewise, the ``4c4'' means that there is a change between line 4 in the first file and line 4 in the second. The ``<'' refers to a line in the first file, and ``>'' refers to a line in the second file. The ``---'' separates the output from each file.
If you want to compare three files, use the
diff3(C)
command. If you want to compare two sorted files, use
comm(C).