Differences between revisions 4 and 12 (spanning 8 versions)
Revision 4 as of 2008-11-22 23:33:03
Size: 515
Editor: GreyCat
Comment: first-line and clean up of English
Revision 12 as of 2017-02-14 19:48:12
Size: 903
Editor: GreyCat
Comment: Sorry, but the substitution-inside-here-doc is not safe. There's no guarantee bash will slurp the old content before overwriting it.
Deletions are marked like this. Additions are marked like this.
Line 5: Line 5:
To insert content at the beginning of a file, you can use an editor: To insert content at the beginning of a file, you can use an editor, for example `ex`:
Line 7: Line 7:
ed -s file << EOF
1i
ex file << EOF
0a
Line 16: Line 16:
or [[http://bash-hackers.org/wiki/doku.php?id=howto:edit-ed|ed]]:
{{{
printf '%s\n' 0a "line 1" "line 2" . w | ed -s file
}}}

`ex` will also add a newline character to the end of the file if it's missing.
Line 22: Line 29:
or lots of other solutions. Some people insist on using the `sed` hammer to pound in all the screws:
{{{
sed "1iTEXTTOPREPEND" filename > tmp &&
mv tmp filename
}}}

There are lots of other solutions as well.

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 insert content at the beginning of a file, you can use an editor, for example ex:

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

or ed:

printf '%s\n' 0a "line 1" "line 2" . w | ed -s file

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

Some people insist on using the sed hammer to pound in all the screws:

sed "1iTEXTTOPREPEND" filename > tmp &&
mv tmp filename

There are lots of other solutions as well.

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