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:
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- My 10 UNIX Command Line Mistakes
- 10 Greatest Open Source Software Of 2009
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- Top 20 OpenSSH Server Best Security Practices
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Linux Video Editor Software
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!
- Email FAQ to a friend
- Download PDF version
- Printable version
- Comment RSS feed
- Last Updated: 08/23/08



{ 5 comments… read them below or add one }
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
Even simpler would be:
sed -i ‘1i Prepended line’ /tmp/newfile
You can also use tac (cat backwards) to make it work. It will print the file from end to beginning.
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.
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