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?


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
some text
you want to insert
goes here
  • 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
  • re. sed -i ... a very good point. When it acts on a symlink, eg. fln, the end result is two "normal" files! The original is unchanged, and the symlink simply disappears and is replaced by a modified "normal" file of the same name. Not a good thing! ... I then tested sed -e '...' fln | sponge fln ... sponge handled the symlink correctly ... @Chris Down, Thanks for heads-up on this issue... – Peter.O Sep 18 '11 at 12:12

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

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

cat f2
  • nice answer abc. See my own one for a modification of yours – hmontoliu Sep 17 '11 at 9:53

+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 
hmontoliu@ulises:/tmp$ sed -i '1 s/^/foobar\n/' f1
hmontoliu@ulises:/tmp$ cat f1

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