Issue
This is probably a complex solution.
I am looking for a simple operator like ">>", but for prepending.
I am afraid it does not exist. I'll have to do something like
mv myfile tmp cat myheader tmp > myfile
Anything smarter?
Solution
The hack below was a quick off-the-cuff answer which worked and received lots of upvotes. Then, as the question became more popular and more time passed, outraged people started reporting that it sorta worked but weird things could happen, or it just didn't work at all, so it was furiously downvoted for a time. Such fun.
The solution exploits the exact implementation of file descriptors on your system and, because implementation varies significantly between nixes, it's success is entirely system dependent, definitively non-portable, and should not be relied upon for anything even vaguely important.
Now, with all that out of the way the answer was:
Creating another file descriptor for the file (exec 3<> yourfile
) thence writing to that (>&3
) seems to overcome the read/write on same file dilemma. Works for me on 600K files with awk. However trying the same trick using 'cat' fails.
Passing the prependage as a variable to awk (-v TEXT="$text"
) overcomes the literal quotes problem which prevents doing this trick with 'sed'.
#!/bin/bash
text="Hello world
What's up?"
exec 3<> yourfile && awk -v TEXT="$text" 'BEGIN {print TEXT}{print}' yourfile >&3
Answered By - John Mee