知道两个二进制文件是否相同(除了时间戳)最简单的方法是什么(在Ubuntu Linux上使用图形工具或命令行)?我不需要提取差值。我只需要知道它们是否相同。


当前回答

为了寻找闪存缺陷,我不得不写这个脚本,它显示所有包含差异的1K块(不仅仅是cmp -b所做的第一个)

#!/bin/sh

f1=testinput.dat
f2=testoutput.dat

size=$(stat -c%s $f1)
i=0
while [ $i -lt $size ]; do
  if ! r="`cmp -n 1024 -i $i -b $f1 $f2`"; then
    printf "%8x: %s\n" $i "$r"
  fi
  i=$(expr $i + 1024)
done

输出:

   2d400: testinput.dat testoutput.dat differ: byte 3, line 1 is 200 M-^@ 240 M- 
   2dc00: testinput.dat testoutput.dat differ: byte 8, line 1 is 327 M-W 127 W
   4d000: testinput.dat testoutput.dat differ: byte 37, line 1 is 270 M-8 260 M-0
   4d400: testinput.dat testoutput.dat differ: byte 19, line 1 is  46 &  44 $

免责声明:我在5分钟内破解了脚本。它不支持命令行参数,也不支持文件名中的空格

其他回答

有一种相对简单的方法来检查两个二进制文件是否相同。

如果你在编程语言中使用文件输入/输出;您可以将这两个二进制文件的每一位存储到它们自己的数组中。

在这一点上,检查非常简单:

if(file1 != file2){
    //do this
}else{
    /do that
}

我最终使用hexdump将二进制文件转换为十六进制表示,然后在meld / kompare /任何其他diff工具中打开它们。我不像你,我要找的是文件中的差异。

hexdump tmp/Circle_24.png > tmp/hex1.txt
hexdump /tmp/Circle_24.png > tmp/hex2.txt

meld tmp/hex1.txt tmp/hex2.txt

标准的unix diff将显示文件是否相同:

[me@host ~]$ diff 1.bin 2.bin
Binary files 1.bin and 2.bin differ

如果该命令没有输出,则意味着文件没有差异。

试试不同的

简单的回答:使用-s开关运行diff。

长话短说:继续往下读。


举个例子。让我们先创建两个包含随机二进制内容的文件:

$ dd if=/dev/random bs=1k count=1 of=test1.bin
1+0 records in
1+0 records out
1024 bytes (1,0 kB, 1,0 KiB) copied, 0,0100332 s, 102 kB/s

                                                                                  
$ dd if=/dev/random bs=1k count=1 of=test2.bin
1+0 records in
1+0 records out
1024 bytes (1,0 kB, 1,0 KiB) copied, 0,0102889 s, 99,5 kB/s

现在让我们复制第一个文件:

$ cp test1.bin copyoftest1.bin

现在test1.bin和test2.bin应该是不同的:

$ diff test1.bin test2.bin
Binary files test1.bin and test2.bin differ

... test1.bin和copyoftest1.bin应该是相同的:

$ diff test1.bin copyoftest1.bin

但是等等!为什么没有输出?!?

答案是:这是有意为之。在相同的文件上没有输出。

但是有不同的错误代码:

$ diff test1.bin test2.bin
Binary files test1.bin and test2.bin differ

$ echo $?
1


$ diff test1.bin copyoftest1.bin

$ echo $?
0

幸运的是,现在你不必每次都检查错误代码,因为你可以使用-s(或——report- identity -files)开关来让diff变得更详细:

$ diff -s test1.bin copyoftest1.bin
Files test1.bin and copyoftest1.bin are identical

你可以使用MD5哈希函数来检查两个文件是否相同,这样你就不能看到低层次的差异,但这是一个快速比较两个文件的方法。

md5 <filename1>
md5 <filename2>

如果两个MD5哈希值(命令回显)相同,则两个文件没有区别。