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?
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
0a
some text
you want to insert
goes here
.
w
EOF
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
+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
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-i
on the symlink. – Chris Down Sep 17 '11 at 13:08sed -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 testedsed -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