Prepend a text to a file.

sed -i '1s/^/text to prepend\n/' file1
Using the sed -i (inline), you can replace the beginning of the first line of a file without redirecting the output to a temporary location.

By: xeor
2011-06-25 12:02:11

4 Alternatives + Submit Alt

What Others Think

Sed has the -i switch for "in-place" editing. First of all, only some implementations of sed (GNU sed and BSD sed AFAIK) support -i. It's a nonstandard extension, and as such not universally available. According to the documentation (at least GNU sed's), what sed does when -i is specified is create a temporary file, send output to that file, and at the end, that file is renamed to the original name. This can be verified with strace; even without strace, a simple "ls -i" of the file before and after sed operates will show two different inode numbers.
RanyAlbeg · 551 weeks and 5 days ago
But at least it does it for us.
kaedenn · 551 weeks and 4 days ago
In a nonstandard way. And it makes sense, since sed is a STREAM editor so the "in-place" option *should* be a nonstandard one by that logic.
RanyAlbeg · 551 weeks and 4 days ago
A good use of this would be: sed -i '1s/^/#!\/usr\/bin\/env python\n\n/'
ewilson · 551 weeks and 3 days ago
echo "text to prepend $(cat output.log)" > output.log
lapinpt · 360 weeks and 3 days ago
echo "text to prepend" | cat - output.log | sponge output.log
lapinpt · 360 weeks and 3 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this? is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands

Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.


Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: