BASH: Prepend A Text / Lines To a File

by Vivek Gite · 5 comments

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

Featured Articles:

Want to read Linux tips and tricks, but don't have time to check our blog everyday? Subscribe to our daily email newsletter to make sure you don't miss a single tip/tricks. Subscribe to our weekly newsletter here!

{ 5 comments… read them below or add one }

1 Sean 08.23.08 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

2 Professor Fapsanders 08.23.08 at 7:19 pm

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

3 mike 08.24.08 at 5:51 pm

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

4 bc 12.29.08 at 4:15 am

Thread’s old, I know, but I wanted to note that tac — at least in the version I have in Cygwin, is not fully “cat in reverse” alas.

As you say, it’ll print from the end — but it won’t take an argument like this:

tac >> somefilethatyouwanttoPREPENDtextto

Just thought I’d note that for others who might be searching the same issue as the OP.
This seems like such an obviously useful utility it’s unbelievable what a pita it is.

5 nairbv 08.17.09 at 10:57 am

I tried the perl command (same one suggested to me by someone on IRC) and it didn’t work. It just printed to stdout and left the file unchanged. I’m kind of surprised two different people suggested the exact same non-working command, so I must be doing something wrong. What could I be doing wrong though??

I like the sed command, but I needed to add more than one line (and my text contained special characters).

This worked for me:

sed -i ‘1{h; r headerfile.txt
D;}
2{x; G; }
‘ filetoedit.txt

I’m not even really sure how it works, I just combined bits of code from a couple of random scripts I saw elsewhere. I should learn more sed :-P

this also worked:

for FILE in `find . -iname “*.php”`
do
cat header.php | cat – $FILE > /tmp/mytmpfile && mv /tmp/mytmpfile $FILE
done

Leave a Comment

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

Previous FAQ:

Next FAQ:

nixCraft FAQ PDF Collection Now Available To All