Sunday, 27 April 2014

Bash scripting: append a line at the beginning of a text file (prepend?)

Everyone knows how to add a line at the end of a text file with the following command:

echo "my text" >> somefile.txt

What if you want to add "my text" line at the beginning of somefile.txt instead of the end? Would this be called 'prepend'?

You will find below the most elegant solutions I found (here mostly):

Easiest to remember 
echo 'task goes here' | cat - somefile.txt > temp && mv temp somefile.txt

Without having to move files around (not recommended for long files)
echo "$(echo 'my text' | cat - somefile.txt)" > somefile.txt

Shortest and my favourite (but many people find sed too obscure)
sed -i '1imy text' somefile.txt
(Don't forget to add the 1i at the beginning of the text as above)