--- layout: page author: Alessandro Luini category-page: advanced category-title: Advanced commands tags: difference lines diff file separating title: diff ---
diff analyzes two files and prints the lines that are different. Essentially, it outputs a set of instructions for how to change one file to make it identical to the second file.
To activate the diff command, we must take as parameters two or more
files that we want to compare and it will give us the output of
different lines.
For example let's say we have two files, file1.txt and file2.txt.
If file1.txt contains the following four lines of text:
- I need to buy apples.
- I need to run around the park.
- I need to wash the dog.
- I need to get the car detailed.
...and file2.txt contains these four lines:
- I need to buy apples.
- I need to do the laundry.
- I need to wash the dog.
- I need to get the dog detailed.
...then we can use diff to automatically display for us which lines differ between the two files with this command:
diff file1.txt file2.txt
...and the output will be:
2,4c2,4
< I need to run the laundry.
< I need to wash the dog.
< I need to get the car detailed.
---
> I need to do the laundry.
> I need to wash the car.
> I need to get the dog detailed.
In our output above, "2,4c2,4" means: "Lines 2 through 4 in the first file need to be changed to match lines 2 through 4 in the second file.
File1.txt | File2.txt |
---|---|
apples | apples |
oranges | kiwis |
kiwis | carrots |
carrots | grapefruits |
diff -c file1.txt file2.txtOur output will be like the following:
*** file1.txt 2014-08-21 17:58:29.764656635 -0400The first two lines of this output show us information about our "from" file (file 1) and our "to" file (file 2). It lists the file name, modification date, and modification time of each of our files, one per line. The "from" file is indicated by "***", and the "to" file is indicated by "---"..
--- file2.txt 2014-08-21 17:58:50.768989841 -0400
***************
*** 1,4 ****
apples
- oranges
kiwis
carrots
--- 1,4 ----
apples
kiwis
carrots
+ grapefruits<
Character | Meaning |
---|---|
! | Indicates that this line is part of a group of one or more lines that needs to change. There is a corresponding group of lines prefixed with "!" in the other file's context as well. |
+ | Indicates a line in the second file that needs to be added to the first file. |
- | Indicates a line in the first file that needs to be deleted. |
diff -u file1.txt file2.txtwill output:
--- file1.txt 2014-08-21 17:58:29.764656635 -0400The output is similar to above, but as you can see, the differences are "unified" into one set.
+++ file2.txt 2014-08-21 17:58:50.768989841 -0400
@@ -1,4 +1,4 @@
apples
-oranges
kiwis
carrots
+grapefruits