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
sed -i '1 ianything' file
sed -i '1i text' filename
For non-GNU sed
You need to hit the return key immediately after the backslash
1i and after
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 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 a.txt <<eof 1 insert Sunday . xit eof