Tuesday, May 29, 2012

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

No comments:

Post a Comment