How to prepend 8 bytes of data to a binary file in Linux?

Here is one way to do that.

printf "\x68\x65\x6c\x6c\x6f\x20\x77\x6f" | cat - oldfile > newfile

The argument to printf is a sequence of 8 bytes in hex. Just replace the values I used (which are the ASCII characters "hello wo") with yours.


it is not 'the' command, it is 'a bunch of commands' (in good old unix tradition):

  • put your 8 bytes to a file
  • append the original file to that file
  • rename the new file to the name of the original file.

or:

% echo -n "12345689" > new_file
% cat original >> new_file
% mv new_file original

or, if you need to read the 8 bytes from somewhere else:

% dd if=inputstream of=new_file bs=1 count=8

and then continue as above.


This is not a proper answer to the original question, but merely a comment to address the very appropriate concern in the comment of @mxmlnkn

So, I need to prepend 256kB to a 120GB file and I don't want to wait 30 minutes to completely copy and write the whole 120GB ... is there no way?

Web search for 'fallocate prepend to file', this should show you a few StackExchange-based answers (EDIT: e.g. https://stackoverflow.com/a/37884191/9378469).

The fallocate approach, given Linux 4.1+ (XFS) or 4.2+ (XFS, ext4) allows you to insert filesystem-page-sized holes in files, hopefully in constant time. This may or may not be sufficiently flexible for your issue.