There is no way to insert an arbitrary amount of text at the start of a file that doesn't involve rewriting the entire file. This applies no matter what language or tool that you use.
You might get a speedup by using something other than sed
to do this1, but the bottleneck is going to be disk / file system IO.
To get better performance:
- treat the data as bytes and copy with a large buffer using
read(2)
and write(2)
syscalls, or
- use the
sendFile(2)
syscall so that the data doesn't need to be copied via a user space buffer, or
- if the data being inserted is (or can be padded to) an exact multiple of the file system block size and the file system supports
fallocate(2)
then you can use this to insert the data without copying2.
C is probably the best language for coding this.
Alternatively, if you wanted to stick with existing command line utilities, using cat
or dd
with the appropriate flags would probably be faster than sed
.
1 - sed
will most likely be splitting the input into lines and then reassembling the lines in a user-space buffer. This is unnecessary.
2 - The padding might consist of additional whitespace or "comment" lines ... assuming that the application that is reading the file can deal with these. If it can, see https://stackoverflow.com/a/59571893/139985 for example code to get you started.