Comparing files using diff and cmp

The diff command gives details of differences between two files. The cmp command simply tells you whether two files are the same or different.

cmp command

The cmp command simply gives a yes|no answer. Ideal for comparing binary files. If the files are identical, no result is printed. If the files differ, the filename and the byte where the first difference is encountered is returned.

$ cmp one.txt two.txt

diff command

$ diff one.txt two.txt

The results would be something like the following:

14c14
< txt txt txt
---
> text text text

The first line indicates the line number(s) which are different between files. The letter c indicates that line 14 must be changed for them to match. The < symbol refers to the text in the first file. > symbol refers to the second file.

Suppose we the following two text files, a file a.txt

abc
bcd
wxy
xyz

and a file b.txt

abc
bcd
cde
def
efg
ghi
wxy
xyz

When I run a diff command

$ diff a.txt b.txt

I get the following result

2a3,6
> cde
> def
> efg
> ghi

2a3 indicates that new lines have been added between lines 2 and 3. The number 6 indicates that the addition ends on line 6. So now, line 3 in a.txt is equivalent to line 7 in b.txt.

To list files that are different in a directory tree:

$ diff -uwrq dir1 dir2

To ignore case:

$ diff -i f1 f2

To ignore repeat blank spaces and ignore case:

diff -ib f1 f2