Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo >> style appending, but to the beginning of a file

Tags:

shell

unix

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?

like image 222
Mikko Ohtamaa Avatar asked May 23 '12 14:05

Mikko Ohtamaa


3 Answers

In 2 steps:

content=$(cat file.txt) # no cat abuse this time
echo -en "foobar\n$content" >file.txt
like image 162
ott-- Avatar answered Oct 01 '22 08:10

ott--


This is nonstandard, but if your sed supports -i you can do:

sed -i '1i\
Foobar' file.txt
like image 39
William Pursell Avatar answered Oct 01 '22 06:10

William Pursell


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.

like image 36
Samuli Pahaoja Avatar answered Oct 01 '22 07:10

Samuli Pahaoja