Comparing files on the unix command line

Suppose I have two files: A and B, and the length Of (A) lengthOf (B). Is there a unix utility to indicate if file B duplicates file A for the first bytes of length Of (A)?

If I do "diff AB", the output will be all the "extra stuff" in file B that skips the point; I don't care what else could be in file B.

If I do "comm AB", then I have to visually check that nothing appears in the column in "only in A". This can be difficult when lengthOf (B) β†’ lengthOf (A), although I suppose it can be tamed grep.

+4
source share
5 answers

This seems a lot better than creating a temporary file:

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

Check the exit status to make sure that the first bytes of these files are really equal.

Update: as requested by 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 

In addition, on MacOS X you should use:

 SIZE=`stat -f %z filename` 
+5
source

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

I believe that this requires creating at least one temporary file, but any comments will be appreciated :)

+3
source

Perhaps create a temporary file with the appropriate contents b up to the length?

Bit of evil, but:

 SIZE=`stat -c %s filea` head -c$SIZE fileb >tempfile diff filea tempfile EXIT=$? rm tempfile exit $EXIT 
+1
source
 head -c`stat -c %s filea` fileb |diff -q filea - 
+1
source

Write a custom awk script for it.

-2
source

Source: https://habr.com/ru/post/1285760/


All Articles