BASH: Prepend A Text / Lines To a File
Q. I can append text to a file using >> operator but how do I prepend a text to a file? I want the opposit of >> operation?
A. There is no prepend operator, however there are many ways to do the same. You can use ed, sed, perl, awk and so on.
Prepend a text using a temporary file
Here is simple solution using a temporary file to prepend text:
echo 'line 1' > /tmp/newfile echo 'line 2' >> /tmp/newfile cat yourfile >> /tmp/newfile cp /tmp/newfile yourfile
Here is one line solution:
echo "text"|cat - yourfile > /tmp/out && mv /tmp/out yourfile
Capture each and every moment of life with a FREE 4 GB SD memory card with the purchase of select digital cameras from Canon, Nikon, Pentax and others from Amazon
E-mail
Print
Can't find an answer to your question? Contact us
Related Other Helpful FAQs:
- Howto: Linux command line utilities for removing blank lines from text files
- Delete text or paragraph between two sections using sed
- Shell: How To Remove Duplicate Text Lines
- Linux / UNIX View Only Configuration File Directives ( uncommented lines of a config file )
- Howto delete empty lines using sed command under Linux / UNIX
Discussion on This FAQ
Leave a Reply
We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!
Tags: append, awk, Bash, echo line, mv, prepend, shell scripting, temporary file



August 23rd, 2008 at 2:11 pm
perl -p -i -e ‘BEGIN { print “First line\n” }’ originalfile
should work without needing an explicit temp file
If you’re going to use these commands in a script, though, “man mktemp” first.
Sean
August 23rd, 2008 at 7:19 pm
Even simpler would be:
sed -i ‘1i Prepended line’ /tmp/newfile
August 24th, 2008 at 5:51 pm
You can also use tac (cat backwards) to make it work. It will print the file from end to beginning.