You cannot insert content at the beginning of a file. The only thing you can do is either replace existing content or append bytes after the current end of file.
Use sed 's insert ( i ) option which will insert the text in the preceding line. 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 ).
The operator '>' writes output to a new file, or to an existing file; in which case it wipes off everything which is previously present in the file. The operator '>>' on the other hand appends output at the end of an existing file. However, there is no dedicated operator to write new text to the beginning of a file.
sed
can operate on an address:
$ sed -i '1s/^/<added text> /' file
What is this magical 1s
you see on every answer here? Line addressing!.
Want to add <added text>
on the first 10 lines?
$ sed -i '1,10s/^/<added text> /' file
Or you can use Command Grouping
:
$ { echo -n '<added text> '; cat file; } >file.new
$ mv file{.new,}
If you want to add a line at the beginning of a file, you need to add \n
at the end of the string in the best solution above.
The best solution will add the string, but with the string, it will not add a line at the end of a file.
sed -i '1s/^/your text\n/' file
If the file is only one line, you can use:
sed 's/^/insert this /' oldfile > newfile
If it's more than one line. one of:
sed '1s/^/insert this /' oldfile > newfile
sed '1,1s/^/insert this /' oldfile > newfile
I've included the latter so that you know how to do ranges of lines. Both of these "replace" the start line marker on their affected lines with the text you want to insert. You can also (assuming your sed
is modern enough) use:
sed -i 'whatever command you choose' filename
to do in-place editing.
Use subshell:
echo "$(echo -n 'hello'; cat filename)" > filename
Unfortunately, command substitution will remove newlines at the end of file. So as to keep them one can use:
echo -n "hello" | cat - filename > /tmp/filename.tmp
mv /tmp/filename.tmp filename
Neither grouping nor command substitution is needed.
To insert just a newline:
sed '1i\\'
You can use cat -
printf '%s' "some text at the beginning" | cat - filename
To add a line to the top of the file:
sed -i '1iText to add\'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With