fuzzybear3965
fuzzybear3965

Reputation: 263

Insert bytes into file using shell

I would like to use a linux shell (bash, zsh, etc.) to insert a set of known bytes into a file at a certain position. Similar questions have been asked, but they modify in-place the bytes of a file. These questions don't address inserting new bytes at particular positions.

For example, if my file has a sequence of bytes like \x32\x33\x35 I might want to insert \x34 at position 2 so that this byte sequence in the file becomes \x32\x33\x34\x35.

Upvotes: 2

Views: 3726

Answers (1)

oguz ismail
oguz ismail

Reputation: 50795

You can achieve this using head, tail and printf together. For example; to insert \x34 at position 2 in file:

{ head -c 2 file; printf '\x34'; tail -c +3 file; } > new_file

For POSIX-compliance, \064 (octal representation of \x34) can be used.

To make this change in-place, just move new_file to file.


No matter which tool(s) you use, this operation will cost lots of CPU time for huge files.

Upvotes: 3

Related Questions