How to insert text before the first line of a file?

Use sed's insert (i) option which will insert the text in the preceding line.

sed '1 i\

Question author's update:

To make it edit the file in place - with GNU sed - I had to add the -i option:

sed -i '1 i\anything' file

Also syntax

sed  -i '1i text' filename

For non-GNU sed

You need to hit the return key immediately after the backslash 1i\ and after first_line_text:

sed -i '1i\
first_line_text
'

Also note that some non-GNU sed implementations (for example the one on macOS) require an argument for the -i flag (use -i '' to get the same effect as with GNU sed).

For sed implementations that does not support -i at all, run without this option but redirect the output to a new file. Then replace the old file with the newly created file.


Echo is used to get the text. Cat filename - prints the file in the console and > uses it to send to another file filename1 and then we move filename1 to filename to get the text inserted to the first line of desired file.

  (echo "some text" && cat filename) > filename1 && mv filename1 filename

You can use the POSIX tool ex:

ex a.txt <<eof
1 insert
Sunday
.
xit
eof

https://pubs.opengroup.org/onlinepubs/9699919799/utilities/ex.html