Command Line – Insert a Line at the Top of a Text File

aptbashcommand line

I want to insert text at the top of an already existing file. How can I achieve this. I tried echo and tee but was not successful.

I was trying to insert repo line at the top of sources.list file from terminal.

Note

I need an one line quick solution, because another answer's method was known to me already

Best Answer

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.