3

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?

2

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks,but i wanted to use shell not python
@CKvir OK. Shell approach added but note that problems are inherent.
If i want to change second line or other line how can i do? 0000010 ffff ffff ffff ffff ffff ffff AAAA ffff ...... 0000030 ffff ffff ffff ffff BBBB ffff ffff ffff
And also there have some problem ,either use python or shell the file size will change, i dont want file size change and other binary value still maintain 0xff, is that possible?
In my tests, there was no change in file size for either method.
0

You can just use vim -b bin-file-name. This would start Vim in binary mode, which allows you to do anything to any file, as long as you know what you are doing.

1 Comment

The question was about editing in a shell script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.