views:

330

answers:

5

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.

A: 

Write a custom awk script for it.

samoz
+3  A: 

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 :)

altCognito
You can use the '-' argument to diff. This tells actually means "open stdin": `head -c 100 a| diff - b` This will compare the 1st 100 bytes in a to all of b.
Nathan Fellman
+1  A: 

Maybe create a temporary file with the appropriate contents of b to the length of a?

Bit evil, but:

SIZE=`stat -c %s filea`
head -c$SIZE fileb >tempfile
diff filea tempfile
EXIT=$?
rm tempfile
exit $EXIT
Douglas Leeder
+5  A: 

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`
admp
+1: nice one! Maybe you can add a line about how to test for exist status 'echo $?' or something :)
xk0der
+1  A: 
head -c`stat -c %s filea` fileb |diff -q filea -
Dolphin