Is there any nice trick in UNIX shell to append lines to the beginning of a file? E.g. akin to
echo "Foobar" >> file.txt
... but instead new lines would prepend the existing ones?
In 2 steps:
content=$(cat file.txt) # no cat abuse this time
echo -en "foobar\n$content" >file.txt
This is nonstandard, but if your sed supports -i you can do:
sed -i '1i\
Foobar' file.txt
I'd keep it simple. The easiest and probably fastest solution is straightforward:
(echo "Foobar"; cat file.txt) >tmpfile
cp tmpfile file.txt
rm tmpfile
If it doesn't matter that file.txt's inode changes, replace the "cp" by "mv". A solution significantly faster than this is not possible, because Unix filesystem semantics don't support prepending to a file, only appending.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With