I have two files with sizes 124665 and 124858 in bytes and want to check whether file1 is a prefix of file2 or not.
Supposing you have the size of
file1 in the variable
FILE1_SZ and your
head implementation supports the (non-standard)
if head -c "$FILE1_SZ" file2 | cmp -s - file1; then echo "file1 is a prefix of file2" else echo "file1 is not a prefix of file2" fi
If your system has the
cmp command from GNU
diffutils, then one option is
cmp -n 124665 file1 file2
to compare at most the first 124665 bytes of the two files and report if they differ - or, more generally
cmp -n "$(wc -c < file1)" file1 file2
cmp can solve the problem in an easier way:
cmp file1 file2
There are four possible outputs (barring some sort of error).
No output: the files are identical.
cmp: EOF on file1: file1 is a prefix of file2.
cmp: EOF on file2: file2 is a prefix of file1.
file1 file2 differ: byte NNN, line MMM: Neither is a prefix of the other.
Unfortunately this is a little awkward to use in a script, since these cases don't seem to be distinguished in the exit code. Moreover, the
EOF on file1 messages go to stderr, while the
file1 file2 differ message goes to stdout.
I presume that other versions of
cmp do something similar, but I have not checked.