Linux: HEX edit and diff in a shell

Hi,

let us assume you want to edit a binary file /tmp/binfile and you want to replace all strings matches to “sda” by “hda”.

gnu sed can edit bin files by the \xnn hex notation. The option –in-place changes the original file and makes a backup copy with a file extension .org

michael@devdeb ~#  sed -e 's/\x73\x64\x61/\x68\x64\x61/g' /tmp/binfile --in-place=.org

Compare both files. Option -y compares the files and prints the files side by side to the console. -W set the outputwidth to 138 characters so that the complete hex dump is visible, otherwise the width of the hex dumps is truncated. colordiff is a wrapper for diff with colored output. Option –suppress-common-lines suppress printing identical lines.

michael@devdeb ~# diff -y -W 138 <(xxd /tmp/binfile) <(xxd /tmp/binfile.org)
michael@devdeb ~# colordiff -y -W 138 <(xxd /tmp/binfile) <(xxd /tmp/binfile.org)

If you want to set a specific byte use dd instead of sed. For example Byte 17 to 0x01. Note:For the first byte in File seek=0x00.

michael@devdeb ~# printf '\x01' |dd of=/tmp/binfile bs=1 seek=16 count=1 conv=notrunc

Or 3 Bytes at 0x10/16

michael@devdeb ~# printf '\x01\x02\x03' |dd of=/tmp/binfile bs=1 seek=16 count=3 conv=notrunc

Michael

Leave a Reply