How to insert a text at the beginning of a file?

user219882 picture user219882 · Mar 2, 2012 · Viewed 279.5k times · Source

So far I've been able to find how to add a line at the beginning of a file but that's not exactly what I want. I'll show it on a example

File content

some text at the beginning

Result

<added text> some text at the beginning

It's similar but I don't want to create any new line with it...

I would like to do this with sed if possible.

Answer

kev picture kev · Mar 2, 2012

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,}