Prepend Text to a File at the Command Line
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.