diff:比较两个文件的不同

xiaohai 2021-06-15 11:33:03 4110人围观 标签: Linux 
简介diff命令可以逐行比较纯文本文件的内容,并输出文件的差异
说明

  diff命令可以逐行比较纯文本文件的内容,并输出文件的差异

格式

  diff [option] [file1] [file2]

常用参数说明
  • -y:以并列的方式显示文件的异同之处
  • -c:使用上下文的输出方式
  • -W:在使用-y参数时,指定显示宽度
  • -u:使用统一的格式输出
示例

1、默认情况下

[root@localhost ~]# cat diff1.txt 
i
am
is
xiaohai
today
[root@localhost ~]# cat diff2.txt 
hello
world
is
xiaohai
very
good

[root@localhost ~]# diff diff1.txt diff2.txt 
1,2c1,2 #第一个文件的1到2行改变成第二个文件的1,2行
< i
< am
---
> hello
> world
5c5,6 #第一个文件的第五号改成第二个文件的5到6行
< today
---
> very
> good

diff默认情况下有三种提示:
a:增加
c:改变
d:删除
5c5,6或者1,2c1,2:字母前面是文件1的行号,字母后面是文件2的行号。其中<开头的是文件1,>开头的属于文件2

2、并排显示差异

[root@localhost ~]# diff -y diff1.txt diff2.txt 
i                                  |    hello
am                                  |    world
is                                is
xiaohai                                xiaohai
today                                  |    very
                                  >    good

#如果上面对比宽度较大,那么可以是-W来控制
[root@localhost ~]# diff -y -W 30 diff1.txt diff2.txt 
i          |    hello
am          |    world
is        is
xiaohai        xiaohai
today          |    very
          >    good

3、上下文输出

[root@localhost ~]# diff -c diff1.txt diff2.txt 
*** diff1.txt    2018-06-04 11:56:25.159021083 -0400
--- diff2.txt    2018-06-04 11:55:56.554022518 -0400
***************
*** 1,5 ****
! i
! am
  is
  xiaohai
! today
--- 1,6 ----
! hello
! world
  is
  xiaohai
! very
! good

命令结果说明如下:
-:表示文件2比文件1少的行数
+:表示文件2比文件1多的行数
!:表示文件2与文件1不同行数

4、统一格式输出

[root@localhost ~]# diff -u diff1.txt diff2.txt 
--- diff1.txt    2018-06-04 11:56:25.159021083 -0400
+++ diff2.txt    2018-06-04 11:55:56.554022518 -0400
@@ -1,5 +1,6 @@
-i
-am
+hello
+world
 is
 xiaohai
-today
+very
+good

5、还可以比较目录

[root@localhost ~]# diff /etc/rc3.d/ /etc/rc6.d/
Only in /etc/rc6.d/: K36mysqld
Only in /etc/rc6.d/: K79iprdump
Only in /etc/rc6.d/: K80iprinit
Only in /etc/rc6.d/: K80iprupdate
Only in /etc/rc6.d/: K90network
Only in /etc/rc3.d/: S10network
Only in /etc/rc3.d/: S20iprinit
Only in /etc/rc3.d/: S20iprupdate
Only in /etc/rc3.d/: S21iprdump
Only in /etc/rc3.d/: S64mysqld

6、修改下diff2.txt文件,删除前两行,然后执行上面的命令

[root@localhost ~]# diff -y diff1.txt diff2.txt 
i                                  <
am                                  <
is                                is
xiaohai                                xiaohai
today                                  |    very
                                  >    good

[root@localhost ~]# diff -c diff1.txt diff2.txt 
*** diff1.txt    2018-06-04 11:56:25.159021083 -0400
--- diff2.txt    2018-06-04 12:07:10.105988728 -0400
***************
*** 1,5 ****
- i
- am
  is
  xiaohai
! today
--- 1,4 ----
  is
  xiaohai
! very
! good

[root@localhost ~]# diff -u diff1.txt diff2.txt 
--- diff1.txt    2018-06-04 11:56:25.159021083 -0400
+++ diff2.txt    2018-06-04 12:07:10.105988728 -0400
@@ -1,5 +1,4 @@
-i
-am
 is
 xiaohai
-today
+very
+good