1

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.

fuzzybear3965
  • 213
  • 2
  • 14

1 Answers1

2

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.

oguz ismail
  • 39,105
  • 12
  • 41
  • 62
  • 1
    This worked great! To be clear, `{ head -c M file; printf %0Ns | tr \0 '\x34'; tail -c +(N+M) file; } > new_file` for inserting N repeated instances of `\x34` starting at position M. – fuzzybear3965 Apr 24 '19 at 03:05
  • 1
    Do you know why `{ head -c 2 file; printf '\x34'; tail -c +3 file; } > file` doesn't work? It outputs only one byte (`\x34`) to `file`. You were right in saying that I'd have to do a `mv new_file file` afterward. But, why? – fuzzybear3965 Apr 24 '19 at 03:06
  • @fuzzybear3965 because by doing that you're writing to a file opened for reading before. here is a better explanation to that [https://unix.stackexchange.com/a/15829/309777]. – oguz ismail Apr 24 '19 at 03:26
  • 1
    That was perfect. You addressed all of my concerns. Thanks so much. – fuzzybear3965 Apr 24 '19 at 03:28