Linux – Understanding of diff output

diff()fileslinux

I have file1.txt

this is the original text  
line2  
line3  
line4  
happy hacking !  

and file2.txt

this is the original text  
line2  
line4  
happy hacking !  
GNU is not UNIX  

if I do: diff file1.txt file2.txt I get:

3d2  
< line3  
5a5  
> GNU is not UNIX  

How is the output generally interpreted? I think that < means removed but what do 3d2 or 5a5 mean?

If I do:

$ diff -u file1.txt file2.txt  
--- file1.txt        2013-07-06 17:44:59.180000000 +0200  
+++ file2.txt        2013-07-06 17:39:53.433000000 +0200  
@@ -1,5 +1,5 @@  
 this is the original text  
 line2  
-line3  
 line4  
 happy hacking !  
+GNU is not UNIX  

The results are clearer but what does @@ -1,5 +1,5 @@ mean?

Best Answer

In your first diff output (so called "normall diff") the meaning is as follows

< - denotes lines in file1.txt

> - denotes lines in file2.txt

3d2 and 5a5 denote line numbers affected and which actions were performed. d stands for deletion, a stands for adding (and c stands for changing). the number on the left of the character is the line number in file1.txt, the number on the right is the line number in file2.txt. So 3d2 tells you that the 3rd line in file1.txt was deleted and has the line number 2 in file2.txt (or better to say that after deletion the line counter went back to line number 2). 5a5 tells you that the we started from line number 5 in file1.txt (which was actually empty after we deleted a line in previous action), added the line and this added line is the number 5 in file2.txt.

The output of diff -u command is formatted a bit differently (so called "unified diff" format). Here diff shows us a single piece of the text, instead of two separate texts. In the line @@ -1,5 +1,5 @@ the part -1,5 relates to file1.txt and the part +1,5 to file2.txt. They tell us that diff will show a piece of text, which is 5 lines long starting from line number 1 in file1.txt. And the same about the file2.txt - diff shows us 5 lines starting from line 1.

As I have already said, the lines from both files are shown together

 this is the original text  
 line2  
-line3  
 line4  
 happy hacking !  
+GNU is not UNIX  

Here - denotes the lines, which were deleted from file1.txt and + denotes the lines, which were added.

Related Question