How do I Compare two files under Linux or UNIX?

Posted on in Categories last updated April 17, 2006

You need to use diff command to display line-by-line difference between two files. The general syntax of diff command as follows:
diff FILE1 FILE2

Where,
FILE1 FILE2: Diff command will examine both file1 and file2 and tells you what changes need to be made for file1 and file2 to match. Please note that diff command point to which lines need be:

  1. Added (a)
  2. Deleted (d)
  3. Changed (c)
  4. Further lines in file1 identified with a less than () symbol and lines in file2 with a grater than (>) symbol.

Examples

diff file1.txt file2.txt

Output:

8c8,9
 URL: www.nixcraft.in
> Email: [email protected]

The contents of both files:

$ cat file1.txt

Output:

Welcome to nixCraft!

If undeliverd return to nixCraft
#404, DC bay area, 2nd phase,
Pune.

Ph: 555-11112223
URL: www.nixcraft.com

$ cat file2.txt

Output:

Welcome to nixCraft!

If undeliverd return to nixCraft
#404, DC bay area, 2nd phase,
Pune.

Ph: 555-11112223
URL: www.nixcraft.in
Email: [email protected]

Side-by-side merge of file differences
You can get a clear-cut visual difference between two text files using the command sdiff:

$ sdiff file1.txt file2.txt

Output:

Welcome to nixCraft!                                            Welcome to nixCraft!

If undeliverd return to nixCraft                                If undeliverd return to nixCraft
#404, DC bay area, 2nd phase,                                   #404, DC bay area, 2nd phase,
Pune.                                                           Pune.

Ph: 555-11112223                                                Ph: 555-11112223
URL: www.nixcraft.com                                         | URL: www.nixcraft.in
                                                              > Email: [email protected]

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Share this on (or read 8 comments/add one below):

8 comment

  1. One more time, cyberciti help me a lot. Thanks and nice site. I became an user site.

  2. What if files are present in two different directories? can we compare that too with sdiff?

  3. Used the first method before scrolling down. Thought: “damn my files have 1000 lines, i’d rather see the diff side by side. I bet someone already build something for this.” *scrolls down* Not disappointed! Thanks! and Linux rocks!

Comments are closed.