Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prepend **heredoc** to a file, in bash

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}
like image 764
branquito Avatar asked Jul 08 '14 14:07

branquito


2 Answers

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
like image 156
anubhava Avatar answered Sep 23 '22 16:09

anubhava


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
like image 27
chepner Avatar answered Sep 23 '22 16:09

chepner