I was using:
cat <<<"${MSG}" > outfile
to begin with writing a message to outfile
, then further processing goes on,
which appends to that outfile
from my awk script.
But now logic has changed in my program, so I'll have to first populate
outfile
by appending lines from my awk
program (externally called from my
bash script), and then as a final step prepend that ${MSG} heredoc
to
the head of my outfile
..
How could I do that from within my bash script, not awk script?
EDIT
this is MSG heredoc
:
read -r -d '' MSG << EOF
-----------------------------------------------
-- results of processing - $CLIST
-- used THRESHOLD ($THRESHOLD)
-----------------------------------------------
l
EOF
# trick to pertain newline at the end of a message
# see here: http://unix.stackexchange.com/a/20042
MSG=${MSG%l}
You can use awk
to insert a multiline string at beginning of a file:
awk '1' <(echo "$MSG") file
Or even this echo
should work:
echo "${MSG}$(<file)" > file
Use a command group:
{
echo "$MSG"
awk '...'
} > outfile
If outfile
already exists, you have no choice but to use a temporary file and copy it over the original. This is due to how files are implemented by all(?) file systems; you cannot prepend to a stream.
{
# You may need to rearrange, depending on how the original
# outfile is used.
cat outfile
echo "$MSG"
awk '...'
} > outfile.new && mv outfile.new outfile
Another non-POSIX feature you could use with cat
is process substitution, which makes the output of an arbitrary command look like a file to cat
:
cat <(echo $MSG) outfile <(awk '...') > outfile.new && mv outfile.new outfile
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With