Bash: replace multiple bytes in binary

I have a binary file zero.bin which contains 10 bytes 0x00 and a data file data.bin which contains 5 bytes 0x01. I want to replace the first 5 bytes of zero.bin with data.bin. I tried

dd if=data.bin of=zero.bin bs=1 count=5

but the .bin zero is truncated, and finally it becomes 5 bytes 0x01. I want to keep the tail 5 bytes 0x00.

+3
source share
3 answers

No problem, just add conv=notrunc:

dd if=data.bin of=zero.bin bs=1 count=5 conv=notrunc
+9
source

You have half the solution; do it in a temporary file tmp.bininstead zero.bin, then

dd if=zero.bin bs=1 seek=5 skip=5 of=tmp.bin
mv zero.bin old.bin # paranoia
mv tmp.bin zero.bin
+1
source

Don't dwell on using dd (1). There are other tools, for example:

(cat data.bin && tail -c +5 zero.bin) > updated.bin
0
source

All Articles