How do you insert a text before the first line in your file?
I've been looking around sed command to add text into a file in a specific line.
This works adding text after line 1:
sed '1 a\
But I want to add it before line 1. That would be so
sed '0 a\
but I get this error: invalid usage of line address 0 .
What's your suggestion?
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