Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Possible Duplicate:
How can I prepend a tag to the beginning of several files?

How do I insert text at the beginning of a file via terminal?

share|improve this question
add comment

marked as duplicate by Gilles, Michael Mrozek Sep 22 '11 at 3:10

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3 Answers

up vote 9 down vote accepted

sed is for editing streams -- a file is not a stream. Use a program that is meant for this purpose, likeed or ex. The -i option to sed is not only not portable, it will also break any symlinks to your file, since it essentially deletes it and recreates it, which is pointless.

ed -s file << EOF
0a
some text
you want to insert
goes here
.
w
EOF
share|improve this answer
1  
A wonderful demonstration of why 'ed' simply refuses to die :) –  Tim Post Sep 17 '11 at 10:58
    
This doesn't break the symbolic link, echo abc>f; ln -s f fln; sed -ie "s/abc/XXX/" f ... GNU sed 4.2.1 –  Peter.O Sep 17 '11 at 13:07
    
@fred You misunderstand what I'm saying. Try using -i on the symlink. –  Chris Down Sep 17 '11 at 13:08
    
Okay, I see what you mean now –  Peter.O Sep 17 '11 at 13:09
    
Thanks Chris your code is short and objective. –  Regis da Silva Sep 18 '11 at 3:27
show 1 more comment

Specify a line range in input file which is restricted to first line, then replace beginning of line with text to add and redirect o/p to a new file

cat f1
one

sed '1,1 s/^/abcdef\n/' < f1 >f2

cat f2
abcdef
one
share|improve this answer
    
nice answer abc. See my own one for a modification of yours –  hmontoliu Sep 17 '11 at 9:53
add comment

+1 for abc's answer because I find his nice sed expression.

However Regis doesn't want two files, he wants to insert text in his file; so I have adapted abc's answer:

hmontoliu@ulises:/tmp$ cat >  f1 
one
^C
hmontoliu@ulises:/tmp$ sed -i '1 s/^/foobar\n/' f1
hmontoliu@ulises:/tmp$ cat f1
foobar
one
share|improve this answer
    
Thank you all, all the codes worked. –  Regis da Silva Sep 18 '11 at 3:28
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.