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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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, people started reporting that it sorta worked but weird things could happen, or it just didn’t work at all. Such fun.
I recommend the ‘sponge’ solution posted by user222 as Sponge is part of ‘moreutils’ and probably on your system by default.
(echo 'foo' && cat yourfile) | sponge yourfileThe solution below 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. Sponge uses the /tmp filesystem but condenses the task to a single command.
Now, with all that out of the way the original 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’.