Prepend Text to a File at the Command Line

Oct 7, 2010 - 2 Comments

Terminal in OS X

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

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

In this case, the file to have text prepended to is ‘file.txt’, replace that with your own document. You may wish to use a backup of the file as you test this out until you understand how it works.

The above command uses cat to dump the file, pbcopy to copy that, then an echo’ed block of text to paste into the file, making hefty use of 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