Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I modify a binary file in a shell script?

Tags:

linux

shell

Is there a command to modify a binary file in the shell?

First, I created a file with all 0xFF values:

dd if=/dev/zero ibs=1K count=1 | tr "\000" "\377" > ./Test.img
hexdump Test.img

Output:

0000000 ffff ffff ffff ffff ffff ffff ffff ffff
*
0000400

Then I wanted to change some byte value like

0000000 aaaa ffff bbbb ffff cccc ffff ffff ffff
*
0000400

How can I change that? Or is there a command in shell script?

like image 923
CK vir Avatar asked Mar 16 '26 05:03

CK vir


1 Answers

Using Python

Python was designed to be binary-clean, so here is one approach:

python -c 'open("New.img", "wb").write( "\xaa\xaa\xff\xff\xbb\xbb\xff\xff\xcc\xcc" + open("Test.img", "rb").read()[10:] )'

We can use hexdump to view the resulting file:

hexdump New.img

Output:

0000000 aaaa ffff bbbb ffff cccc ffff ffff ffff
0000010 ffff ffff ffff ffff ffff ffff ffff ffff
*
0000400

Using shell

The shell is not binary-clean. For example, no shell string can contain the character \x00. Consequently, any approach using shell may be subject to unpleasant surprises. However, if one must, try:

LC_ALL=C; { printf "%s" $'\xaa\xaa\xff\xff\xbb\xbb\xff\xff\xcc\xcc'; tail -c+11 New.img; } >New2.img
like image 160
John1024 Avatar answered Mar 17 '26 20:03

John1024



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!