Linux diff command: compares two text files line by line, listing their differences
Linux diff command Function Description
Use the diff command to compare two text files line by line, listing their differences.
It can perform more complex checks than the comm command, which systematically checks the given file and shows all the different lines in the two files, without requiring prior sorting of the files.
Linux diff command Syntax
diff [option] [file1] [file2]
The meaning of each option in the command is shown in the table:
Option | Description |
---|---|
-b | Ignore end-of-line spaces, and treat one or more spaces in a string as equal |
-c | Ignore end-of-line spaces, and treat one or more spaces in a string as equal |
-e | Output an ed script |
-r | When comparing directories, recursively compare any found subdirectories |
-y | Output in two-column side-by-side format |
-W <n> |
When outputting in parallel format, use the specified column width, n for the number |
-u | Use a uniform output format |
-i | Ignore case differences in file content |
-w | Ignore all the gaps |
-a | All files are treated as text files for line-by-line comparison |
-B | Ignore changes caused by inserting and deleting empty rows |
-q | Report only when documents are different |
-s | Report when two files are identical |
-t | Expand tabs to spaces on output to protect tab alignment of input files |
-x <mode> |
Exclude files with matching patterns |
-X <file> |
When comparing directories, ignore files and directories that match the style of any file included in the specified file |
Linux diff command Demo
Compare apidemos.com.sort.txt and apidemos.com.txt files and list their differences
Compare file1 and file2 files and list their differences
[root@rhel ~]# cat file1
a
aa
[root@rhel ~]# cat file2
a
bb
//View the file contents of files file1 and file2
[root@rhel ~]# diff file1 file2
2c2
< aa
---
> bb
//You can see that the difference between the file1 and file2 files is the aa and bb in the second line
Compare the differences between file1 and file2 files in side-by-side format output
[root@rhel ~]# diff file1 file2-y -W 50
a a
aa |bb
Compare the differences between file1 and file2 files in contextual output format
[root@rhel ~]# diff file1 file2-c
***file1 2013-08-19 00:49:59.047999561+0800
---file2 2013-08-19 00:50:04.042999929+0800
***************
*** 1,2 ****
a
! aa
---1,2----
a
Compare the differences between file1 and file2 files in a uniform format output
[root@rhel ~]# diff file1 file2-u
---file1 2013-08-19 00:49:59.047999561+0800
+++file2 2013-08-19 00:50:04.042999929+0800
@@ -1,2 +1,2 @@
a
-aa
+bb
Compare the differences between dir1 and dir2 directories
[root@rhel ~]# diff dir1 dir2