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.
Pretty simple
echo “new text to be prended” >> file.txt
or
copy text and prepend from a file to a new file
cat file_to_be_added.txt >> file_to_add_text_to.txt
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.
You’re trying too hard…
(echo “Text to prepend”; cat file.txt) > /tmp/tempfile && mv /tmp/tempfile file.txt