How to insert a text at 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 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 > newfilesed '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.