How do I insert a line at the top of a text file using the command line?

It's actually quite easy with sed:

  • sed -i -e '1iHere is my new top line\' filename

  • 1i tells sed to insert the text that follows at line 1 of the file; don't forget the \ newline at the end so that the existing line 1 is moved to line 2.


In general editing in place with a script is tricky, but you can use echo and cat and then mv

echo "fred" > fred.txt
cat fred.txt t.txt >new.t.txt
# now the file new.t.txt has a new line "fred" at the top of it
cat new.t.txt
# can now do the rename/move
mv new.t.txt t.txt

However if you're playing with sources.list you need to add in some validation and bullet-proofing to detect errors etc because you really don't want to loose this. But that's a separate question :-)


./prepend.sh "myString" ./myfile.txt

known that prepend is my custom shell:

#!/bin/sh
#add Line at the top of File
# @author Abdennour TOUMI
if [ -e $2 ]; then
    sed -i -e '1i$1\' $2
fi

Use also a relatif path or absolute path , it should work fine :

./prepend.sh "my New Line at Top"  ../Documents/myfile.txt

Update :

if you want a permanent script for this , open nano /etc/bash.bashrc then add this function at the end of file:

function prepend(){
# @author Abdennour TOUMI
if [ -e $2 ]; then
    sed -i -e '1i$1\' $2
fi

}

Reopen you terminal and enjoy :

prepend "another line at top" /path/to/my/file.txt

And why not use a genuine text editor for that? ed is the standard text editor.

ed -s filename <<< $'1i\nFIRST LINE HERE\n.\nwq'

Or, if you want the commands to be more readable:

ed -s filename < <(printf '%s\n' 1i "FIRST LINE" . wq)
  • 1: go to firstline
  • i: insert mode
  • your stuff you want to insert...
  • .: stop inserting, go back to normal mode
  • wq: write and quit, thank you, good bye.

You can use Vim in Ex mode:

ex -s -c '1i|hello world' -c -x sources.list
  1. 1 select 1st line

  2. i insert new line of text

  3. x save and close