Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare first N bytes of binary files in Linux

I have two binary files with different sizes. I need to compare first N bytes of these files in Linux. I expect that the result is either "yes" (the same) or "no" (not the same), not byte-to-byte comparing. The N may vary from KBs to GBs.

Currently I'm using the following approach:

head -c N input1.dat | rdiff signature >1.sig
head -c N input2.dat | rdiff signature >2.sig
diff 1.sig 2.sig

But I'm wondering if there is another approach, more simple. Thanks.

like image 293
Rom098 Avatar asked Jun 01 '11 15:06

Rom098


People also ask

How do I compare two binary files in Linux?

Use the command cmp to check if two files are the same byte by byte. The command cmp does not list differences like the diff command. However it is handy for a fast check of whether two files are the same or not (especially useful for binary data files).

Can you use diff for binary files?

You can also force diff to report only whether files differ (but not how). Use the --brief ( -q ) option for this. In operating systems that distinguish between text and binary files, diff normally reads and writes all data as text. Use the --binary option to force diff to read and write binary data instead.

Which command is used to print first two bytes?

The head command is also capable of printing the first “n” bytes of a file. In the ASCII character set, each character takes one byte.


1 Answers

Try cmp:

cmp -n <bytes> file1 file2

From the man page: exit status is 0 if inputs are the same, 1 if different, 2 if trouble.

like image 194
Nemo Avatar answered Oct 05 '22 03:10

Nemo