Differences between revisions 1 and 10 (spanning 9 versions)
Revision 1 as of 2008-05-24 07:43:08
Size: 448
Editor: pgas
Comment: How do I prepend a text to a file (the opposite of >>)?
Revision 10 as of 2017-02-14 15:52:50
Size: 1051
Editor: peir-sab-antaeustravel-peer
Comment: here-doc method added
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
[[Anchor(faq90)]] <<Anchor(faq90)>>
Line 3: Line 4:
You cannot do it with bash redirections alone; the opposite of `>>` does not exist....
Line 4: Line 6:
You cannot do it with bash redirections only, ie the opposite of >> does not exist. To insert content at the beginning of a file, you can use an editor, for example `ex`:
Line 6: Line 8:
You can use an editor:
Line 8: Line 9:
ed -s file << EOF
i
ex file << EOF
0a
Line 16: Line 17:
you can use things like: 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.

Or you can rewrite the file, using things like:
Line 21: Line 30:
Some people insist on using the `sed` hammer to pound in all the screws:
Line 22: Line 32:
or a gazillion of other solutions {{{
sed "1iTEXTTOPREPEND" filename > tmp &&
mv tmp filename
}}}

Can also be done using here-docs either on command line or inside a script:

{{{
cat <<EOF >a.txt
This is line 0
$(cat a.txt)
EOF
}}}

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

Can also be done using here-docs either on command line or inside a script:

cat <<EOF >a.txt
This is line 0
$(cat a.txt)
EOF

There are lots of other solutions as well.

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