Unix: prepending a file without a dummy-file? Unix: prepending a file without a dummy-file? unix unix

Unix: prepending a file without a dummy-file?


You can't append to the beginning of a file without rewriting the file. The first way you gave is the correct way to do this.


This is easy to do in sed if you can embed the header string directly in the command:

$ sed -i "1iheader1,header2,header3"

Or if you really want to read it from a file, you can do so with bash's help:

$ sed -i "1i$(<header)" file

BEWARE that "-i" overwrites the input file with the results. If you want sed to make a backup, change it to "-i.bak" or similar, and of course always test first with sample data in a temp directory to be sure you understand what's going to happen before you apply to your real data.


The whole dummy file thing is pretty annoying. Here's a 1-liner solution that I just tried out which seems to work.

    echo "`cat header file`" > file

The ticks make the part inside quotes execute first so that it doesn't complain about the output file being an input file. It seems related to hhh's solution but a bit shorter. I suppose if the files are really large this might cause problems though because it seems like I've seen the shell complain about the ticks making commands too long before. Somewhere the part that is executed first must be stored in a buffer so that the original can be overwritten, but I'm not enough of an expert to know what/where that buffer would be or how large it could be.