One Thing Well

A weblog about simple, useful software.

Follow on Twitter, Google+ or via the feed. Feel free to get in touch. Sponsor the site.

Prepend Text to a File at the Command Line

Prepending text to a file at the command line is a fiddly business. Here are a few ways to do it:

Using the clipboard

On OS X

cat file.txt | pbcopy && echo "Text to prepend" > file.txt && pbpaste >> file.txt

On Linux, with xclip

cat file.txt | xclip -i && echo "Text to prepend" > file.txt && xclip -o >> file.txt

Using a temporary file

echo "Text to prepend" | cat - file.txt > /tmp/tempfile && mv /tmp/tempfile file.txt

Using ed

echo  '0a
Text to prepend
.
w' | ed file.txt

Using sed (my favourite)

sed -i '1i Text to prepend' file.txt

No doubt there are more—and better?—ways to do this: let me know if so.

David suggests using sponge:

(echo "text to prepend"; cat file.txt) | sponge file.txt