Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing files on the unix command line

Suppose I have two files, A and B, and that lengthOf(A) < lengthOf(B). Is there a unix utility to tell if file B duplicates file A for the first lengthOf(A) bytes?

If I do "diff A B", the output will be all the 'extra stuff' in the B file, which misses the point; I don't care what else might be in file B.

If I do "comm A B", then I have to visually inspect that nothing turns up in the column for 'only in A'. This can be difficult when lengthOf(B) >> lengthOf(A), though I suppose it could be tamed with grep.

like image 309
JustJeff Avatar asked Feb 28 '23 16:02

JustJeff


2 Answers

This seems much better than creating temporary file:

SIZE=`stat -c %s filea`
cmp -s -n $SIZE filea fileb # -s for silence

Check the exit status to see whether the first bytes of those files are indeed equal.

Update: as per request of xk0der, here is a longer example:

wormhole:tmp admp$ echo -n "fooa" > one # -n to supress newline
wormhole:tmp admp$ echo -n "foobc" > two
wormhole:tmp admp$ SIZE=`stat -c %s one`
wormhole:tmp admp$ echo $SIZE
4
wormhole:tmp admp$ (cmp -s -n $SIZE one two && echo "equal") || echo "not equal"
not equal
wormhole:tmp admp$ echo -n "fooac" > two # first 4 bytes are equal now
wormhole:tmp admp$ (cmp -s -n $SIZE one two && echo "equal") || echo "not equal"
equal

Also, in MacOS X you have to use:

SIZE=`stat -f %z filename`
like image 96
adomas Avatar answered Mar 05 '23 15:03

adomas


Use head -c to specify the number of bytes for each file and then compare them.

I believe this requires creating at least one temporary file, but would appreciate any comments otherwise :)

like image 39
cgp Avatar answered Mar 05 '23 16:03

cgp