Linux – How to insert a text at the beginning of a file

bashlinuxsed

So far I've been able to find out how to add a line at the beginning of a file but that's not exactly what I want. I'll show it with an 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.

Best Answer

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