I have a partition image that contains a 1MB file populated with random data, and I would like to replace the contents of that file with another 1MB file populated with different random data.

I have done something similar before by creating a file with a known unique string and using sed to replace it e.g. sed -i 's/foobar_corruptiontest/barfoo_corruptiontest/' partition.img

For a solution I imagined something along the lines of:

head -c 1M </dev/urandom >fileA
head -c 1M </dev/urandom >fileB
binary_sed -i 's/<fileA/<fileB/' partition.img

I found a tool bbe which purports to be a sedlike editor for binary files, but unless I am reading the man page wrong it doesn't seem to support file input?

Side-note: In case you are very confused why anyone would want to do this, the context is I am testing verity by corrupting a file in a predictable manner, but it should bear no relevance to the question. In fact please do not consider it in an answer.

  • 3
    The writing part should be easy as dd if=fileB of=partition.img bs=1 seek=$OFFSET conv=notrunc It's getting $OFFSET that's the tricky part. Sure , some variation on grep --byte-offset could do it, if you wanted to create a pattern that matched a 1M file. – infixed May 17 '18 at 13:49
  • 1
    that's tricky but you can imagine combining dd if=samedevice skip=x count= ...| bbe ... | dd seek=x of=samedevice . since input is read before being overwritten that should do it (have a backup...) – A.B May 17 '18 at 13:53

I found a halfway decent solution, but unfortunately it requires a non-standard tool to search for the file offset. I hope that someone can come up with a better answer that only uses standard tools.

Install the tool SearchBin.

head -c 1M </dev/urandom >fileA
head -c 1M </dev/urandom >fileB
OFFSET=$(searchbin -f fileA -m 1 partition.img | head -1 | awk '{print $4}')
dd if=fileB of=paritition.img bs=1 seek=${OFFSET} conv=notrunc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.