How to insert text before the first line of a file?
I've been looking around
sedcommand 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. It would be:
sed '0 a\
but I get this error:
invalid usage of line address 0.
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 i\anything' file
sed -i '1i text' filename
For non-GNU sed
You need to hit the return key immediately after the backslash
sed -i '1i\ first_line_text '
Also note that some non-GNU
sedimplementations (for example the one on macOS) require an argument for the
-i ''to get the same effect as with GNU
Interesting! I'm on Lubuntu 13.10 and `sed '1 i\this text is entered above the existing first line' file` works for me.
Here, using `sed (GNU sed) 4.2.2` just `sed '1 i text to insert' -i file` worked like a charm. Thanks
The `-i` argument to `sed` tells it to edit the file in-place — I have a feeling all of the commenters here were seeing the same behavior, but simply had different expectations. Without `-i`, sed will execute the commands specified and _output_ the results to the terminal, unless you redirect it somewhere else. WITH `-i`, it will actually modify the file on disk, and write the changed version in place of the original. Two different approaches to `sed`-ing a file's contents, depending whether you need to preserve the unaltered version of the input file.
@rudimeier Huh! You're right, it doesn't work on _completely_ empty files. I guess because sed is super-literal, and you can't insert text at line 1 when there _isn't_ a "line 1" in the file. So `touch empty.txt && sed '1i Text' -i empty.txt` will do nothing, whereas `echo > blank.txt && sed '1i Text' -i blank.txt` will result in `blank.txt` containing a line that reads "Text", with a blank line after it.
Well, inserting text into a completely empty file is kind of a pathological case, anyway. I can see how some script might need to be able to handle that case, but in any interactive use the way to "insert" text at the start of an empty file is just `echo "text" > file`. :-)