Prepending is, of course, adding stuff to the front of a file whereas appending is sticking it on the end. Prepending is an affront to sequential file handling and should never be attempted, but if you really want to do it anyway, it got a few of us thinking.
To append stuff to a file it’s easy.
echo New stuff >> existing-file
The first thing that came into our heads was to reverse the file, append the new stuff and then reverse it again. Except “rev” reverses characters, as well as lines, so the stuff you want to append would have to be reversed to it came out the right way and… it was getting messy.
Someone suggested tac to reverse the file line-by-line, which was better, but tac???? Apparently it’s a Linux reverse “cat” that writes stuff out backwards line by line. On Unix it appears to be the equivalent of “tail -r”, but the -r option doesn’t exist on the GNU version. I see that a lot on Linux – they have a cut-down version of some Unix utility and spawn another utility to fill the shortcomings rather than adding it.
But, even with tail -r (or tac) it gets a bit messy – you really need a temp file as far as I can figure it. Does anyone have devious way to avoid it?
So just go for simple. On GNU systems:
echo New stuff | cat <(cat) existing-file > temp && mv temp existing-file
This is only going to work with bash, which has an extension that captures the output of a process and feeds it into stdin: <(....)
. You do the same easily Bourne shell using a named pipe, but it’s just making things more complicated when there’s a simpler solution when a utility uses a – to stand for stdin in a list of file arguments:
echo New stuff | cat - existing-file > temp && mv temp existing-file
But this is still using a temporary file.
Then it was suggested that sed -i
might do it “in place”. If course it’s not in-place on the disk, but it looks neater and you can pretend it’s okay.
echo New Stuff | sed -i "1i $(cat)" existing-file
This was a team effort – Stefan persevered with sed, I added the stdin capture using cat. Note that this is GNU sed – the original sed would require you to specify a backup file extension – i.e. stick a ” after the -i (that’s two single quotes for an empty string). Actually, specifying “.backup” might be wise.
Now back to some real work.