About Linux FAQ

Browse More FAQs:

BASH: Prepend A Text / Lines To a File

Posted by Vivek Gite [Last updated: August 23, 2008]

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:

Discussion on This FAQ

  1. Sean Says:

    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

  2. Professor Fapsanders Says:

    Even simpler would be:
    sed -i ‘1i Prepended line’ /tmp/newfile

  3. mike Says:

    You can also use tac (cat backwards) to make it work. It will print the file from end to beginning.

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!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Tags: , , , , , , ,

Copyright © 2006-2008 nixCraft. All rights reserved - TOS/Disclaimer - Privacy policy - Powered by Open source software.