cmp与diff是linux下好用的两个文件比较工具,相比cmp,diff的用法更强大。
cmp:比较两个文件是以字节比较的,若两文件相同则返回0,否则返回1.
-b:输出不同的字节
-s :以静默模式输出
<code> [root@localhost test]# echo asd> a [root@localhost test]# echo qwe>b [root@localhost test]# cmp a b #不带选项 a b differ: byte 1, line 1 [root@localhost test]# cmp -b a b #输出不同的字节 a b differ: byte 1, line 1 is 141 a 161 q [root@localhost test]# cmp -s a b #以静默模式输出 [root@localhost test]# echo $? 1 </code>
diff:以行比较两个文件
-y:表示输出为两列
-W:表示输出的两列之间宽度
diff 的normal 显示格式有三种提示:
a – add
c – change
d – delete
diff的输出格式有三种:
* 正常格式(normal diff)
* 上下文格式(context diff)
* 合并格式(unified diff)
<code> 例1:正常格式输出 [root@localhost test]# cat a asd qwe 123 [root@localhost test]# cat b qwe asd 123 [root@localhost test]# diff a b 1d0 < asd 2a2 > asd 上面1d0中1表示第一行有变化,d表示删除,0表示第二个文件的0行与变化,具体来说就是第一个文件删除第1行变动为第二个文件的第0行。 例2: [root@localhost test]# cat a asd qwe 123 [root@localhost test]# cat b asd qwe 1234 [root@localhost test]# diff a b 3c3 < 123 --- > 1234 3c3表示第3行不同,第一个文件的第3行变化为第二个文件的第3行 例3:并排格式输出 [root@localhost test]# diff a b -y -W 50 asd asd qwe qwe 123 | 1234 > zxc > fgh </code>
-y:表示输出为两列,-W表示宽度间隔为50
说明:
“|”表示前后2个文件内容有不同
“<”表示后面文件比前面文件少了1行内容 “>”表示后面文件比前面文件多了1行内容
例4:上下文格式输出
<code> [root@localhost test]# diff a b -c *** a 2015-03-31 05:29:30.283034133 -0700 --- b 2015-03-31 05:29:06.922033517 -0700 *************** *** 1,3 **** asd qwe ! 123 --- 1,5 ---- asd qwe ! 1234 ! zxc ! fgh 例5:合并格式输出 [root@localhost test]# diff a b -u --- a 2015-03-31 05:29:30.283034133 -0700 +++ b 2015-03-31 05:29:06.922033517 -0700 @@ -1,3 +1,5 @@ asd qwe -123 +1234 +zxc +fgh </code>
说明:例4和例5
这种方式在开头两行作了比较文件的说明,这里有三中特殊字符:
“+” 比较的文件的后者比前着多一行
“-” 比较的文件的后者比前着少一行
“!” 比较的文件两者有差别的行
<code> 例6:比较文件夹 [root@localhost tmp]# diff test test1 diff test/a test1/a 2,3d1 < qwe < 123 diff test/b test1/b 1,5d0 < asd < qwe < 1234 < zxc < fgh Only in test1: c Only in test1: d Only in test1: d1 Only in test1: d2 Only in test1: d3 说明与以上相同! </code>
例7:打补丁
<code> [root@localhost test]# cat a asd qwe 123 [root@localhost test]# cat b asd qwe 1234 zxc fgh [root@localhost test]# diff -c a b >pat #不同之处存入文件pat [root@localhost test]# patch < pat #打补丁 patching file a [root@localhost test]# cat a asd qwe 1234 zxc fgh [root@localhost test]# cat b asd qwe 1234 zxc fgh </code>