Differences between revisions 4 and 7 (spanning 3 versions)
Revision 4 as of 2008-11-22 23:33:03
Size: 515
Editor: GreyCat
Comment: first-line and clean up of English
Revision 7 as of 2010-05-26 05:12:24
Size: 681
Editor: 99-190-22-125
Comment:
Deletions are marked like this. Additions are marked like this.
Line 5: Line 5:
To do it in 2 commands with sed:
sed "1iTEXTTOPREPEND" filename > tmp
mv tmp filename
Line 7: Line 11:
ed -s file << EOF
1i
ex file << EOF
0a
Line 15: Line 19:
ex will also add a newline character to the end of the file if it's missing.

How do I prepend a text to a file (the opposite of >>)?

You cannot do it with bash redirections alone; the opposite of >> does not exist....

To do it in 2 commands with sed: sed "1iTEXTTOPREPEND" filename > tmp mv tmp filename

To insert content at the beginning of a file, you can use an editor:

ex file << EOF
0a
header line 1
header line 2
.
w
EOF

ex will also add a newline character to the end of the file if it's missing.

Or you can rewrite the file, using things like:

{ echo line; cat file ;} >tmpfile && mv tmpfile file
echo line | cat - file > tmpfile && mv tmpfile file

or lots of other solutions.

BashFAQ/090 (last edited 2017-02-14 19:48:12 by GreyCat)