Prepend text to a file

Oct 7, 2010 - 2 Comments

You can easily prepend text to a file from the command line by using the following command:

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

This uses the pbcopy and pbpaste commands, you may recognize them as the command line front to the Mac OS X clipboard.

You can also prepend any text to the beginning of another text file by using the echo command in conjunction with temporary files:

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

In case this is greek to you, prepending text basically means you are adding additional text to the very beginning of another specified text file.

I prefer the pbcopy/pbpaste method but that is limited to Mac OS X, you can use the echo command in Linux and other Unix variants if you wish.

This handy tip was sent in by Cedrik, who found it on OneThingWell.org.

Enjoy this tip? Subscribe to the OSXDaily newsletter to get more of our great Apple tips, tricks, and important news delivered to your inbox! Enter your email address below:

Related articles:

Posted by: Manish Patel in Command Line, Mac OS X

2 Comments

» Comments RSS Feed

  1. lar3ry says:

    You’re trying too hard…

    (echo “Text to prepend”; cat file.txt) > /tmp/tempfile && mv /tmp/tempfile file.txt

  2. Pete says:

    Both of these are risky – if you screw it up, you end up trashing your original file.

    Not only does the 2nd version work in all UNIXes, but it probably works better if file.txt is a huge (many megabytes) text file.

    This may be even better:

    sed -i.bak -e ’1i\
    Hello there’ x.pl

    This way, at least you keep a backup, just in case.

Leave a Reply

 

Shop for Apple & Mac Deals on Amazon.com

Subscribe to OSXDaily

Subscribe to RSS Subscribe to Twitter Feed Follow on Facebook Subscribe to eMail Updates