Differences between revisions 9 and 11 (spanning 2 versions)
Revision 9 as of 2011-03-15 17:02:32
Size: 903
Editor: GreyCat
Comment: ed
Revision 11 as of 2017-02-14 16:07:10
Size: 1243
Editor: peir-sab-antaeustravel-peer
Comment: here-doc method improved
Deletions are marked like this. Additions are marked like this.
Line 2: Line 2:
Line 6: Line 7:
Line 15: Line 17:
or [[http://bash-hackers.org/wiki/doku.php?id=howto:edit-ed|ed]]:
Line 16: Line 19:
or [[http://bash-hackers.org/wiki/doku.php?id=howto:edit-ed|ed]]:
Line 20: Line 22:
Line 24: Line 25:
Line 28: Line 30:
Some people insist on using the `sed` hammer to pound in all the screws:
Line 29: Line 32:
Some people insist on using the `sed` hammer to pound in all the screws:
Line 35: Line 37:
With bash version >= 4 , this can also be done using here-docs either on command line or inside a script.

PS: Has not been tested in other shells.

{{{
newline="This is line -1"
cat <<EOF >a.txt
$newline #variables are accepted
This is line 0 #fixed string
$(cat a.txt) #the old file - same name is ok
EOF
}}}

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

With bash version >= 4 , this can also be done using here-docs either on command line or inside a script.

PS: Has not been tested in other shells.

newline="This is line -1"
cat <<EOF >a.txt 
$newline       #variables are accepted
This is line 0 #fixed string
$(cat a.txt)   #the old file - same name is ok
EOF

There are lots of other solutions as well.

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