Reputation: 83408
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?
Upvotes: 8
Views: 10988
Reputation: 2720
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.
Upvotes: 3
Reputation: 212258
This is nonstandard, but if your sed supports -i you can do:
sed -i '1i\
Foobar' file.txt
Upvotes: 6
Reputation: 5722
In 2 steps:
content=$(cat file.txt) # no cat abuse this time
echo -en "foobar\n$content" >file.txt
Upvotes: 10