Linux 两文件逐字节比较:cmp命令
cmp命令
用法
1 | cmp file1 file2 |
功能
- 逐字节比较两个文件是否完全相同
- 两个文件完全相同时,不给出任何提示
- 两个文件不同时,打印出第一个不同之处
- 在Windows中有类似的命令COMP
cmp命令用来比较两个文件是否有差异。
- 当相互比较的两个文件完全一样时,则该指令不会显示任何信息。
- 若发现有差异,预设会标示出第一个不通之处的字符和列数编号。
- 若不指定任何文件名称或是所给予的文件名为“-”,则cmp指令会从标准输入设备读取数据。
cmp命令示例
查找两个文件之间的第一个差异的字节和行号
1 | [root@localhost cmp]# cat -n a.txt |
cmp -b:显示差异处的十进制字码和对应字符
[root@localhostf cmp]# cat -n a.txt
1 this is line a
2 this is line b
3 helloworld!
4 this is line d
[root@localhost cmp]# cat -n b.txt
1 this is line a
2 this is line b
3 this is line c
4 this is line d
[root@localhost cmp]# cmp -b a.txt b.txt
a.txt b.txt 不同:第 3 行,第 31 字节为 150 h 164 t
[root@localhost cmp]#
cmp -l:显示出所有不一样的字节
[root@localhost cmp]# cat -n a.txt
1 this is line a
2 this is line b
3 helloworld!
4 this is line d
[root@localhost cmp]# cat -n b.txt
1 this is line a
2 this is line b
3 this is line c
4 this is line d
[root@localhost cmp]# cmp -l a.txt b.txt
31 150 164
32 145 150
33 154 151
34 154 163
35 157 40
36 167 151
37 157 163
38 162 40
40 144 151
41 41 156
42 12 145
43 164 40
44 150 143
45 151 12
46 163 164
47 40 150
51 154 151
52 151 163
53 156 40
54 145 154
55 40 151
56 144 156
57 12 145
cmp:a.txt 已结束
cmp -l输出详解
cmp -l的输出有3列,
- 第1列表示两个文件开始不同的字节序号,也就是具体从第几个字节开始不同。
- 第2列表示文件a.txt当前的字节
- 第3行表示文件b.txt当前的字节
当然光看字节,我们难以理解,可以加上-b选项同时显示对应的字符:
[root@localhost cmp]# cmp -bl a.txt b.txt 31 150 h 164 t 32 145 e 150 h 33 154 l 151 i 34 154 l 163 s 35 157 o 40 36 167 w 151 i 37 157 o 163 s 38 162 r 40 40 144 d 151 i 41 41 ! 156 n 42 12 ^J 145 e 43 164 t 40 44 150 h 143 c 45 151 i 12 ^J 46 163 s 164 t 47 40 150 h 51 154 l 151 i 52 151 i 163 s 53 156 n 40 54 145 e 154 l 55 40 151 i 56 144 d 156 n 57 12 ^J 145 e cmp:a.txt 已结束 [root@localhost cmp]#
可以看到a.txt和b.txt这两个文件从第31个字节处开始不同:
- a.txt的第31个字节是150,对应的是字符h。
- b.txt的第31个字节是164,对应的是字符t。
cmp -s:只比较不显示消息,以命令返回值表示
这样,如果文件相同,则给出值 0,如果不同,则给出值 1,或者如果发生错误,则给出值 2。该命令形式通常用在 shell 步骤中。例如:
1 | if cmp -s prog.c.bak prog.c |
如果两个文件相同,则该部分的shell步骤显示 没有改变
cmp -s用在shell编程中
测试文件:
1 | [root@localhost cmp]# ls |
shell程序:
1 | [root@localhost cmp]# cat isSame.sh |
运行结果:
1 | [root@localhost cmp]# ./isSame.sh |
windows的comp命令示例
1 | G:\Desktop\test\CMD>dir |
cmp参考手册
tldr cmp
1 | [root@localhost cmp]# tldr cmp |
cmp –help
1 | [root@localhost cmp]# cmp --help |
man cmp
1 | CMP(1) User Commands CMP(1) |
参考资料
http://www.linuxso.com/command/cmp.html
https://www.runoob.com/linux/linux-comm-cmp.html
https://man.linuxde.net/cmp