13

I have a bunch of output going through sed and awk.

How can I prefix the output with START and suffix the answer with END?

For example, if I have

All this code
on all these lines
and all these

How could I get:

START
All this code
on all these lines
and all these
END

?

My attempt was:

awk '{print "START";print;print "END"}'

but I got

...
START
    All this code
END
START
    on all these lines
END
START
    and all these
END
17

This works, as indicated by jasonwryan:

awk 'BEGIN{print "START"}; {print}; END{print "END"}'
11

This can be done in sed with

sed -e $'1i\\\nSTART' -e $'$a\\\nEND'

1i means insert before line 1; $a means append after the last line.  The $'…' syntax is bash-specific.  In other shells, you should be able to do this with:

sed -e '1i\Enter
START' -e '$a\Enter
END'Enter
8

If you're already using sed, you can use 1 to match the first line and $ to match the last line (see Scott's answer). If you're already using awk, you can use a BEGIN block to run code before the first line and an END block to run code after the last line (see Michael Durrant's answer).

If all you need to do is add a header and a footer, just use echo and cat.

echo START
cat
echo END

In a pipeline, to run multiple commands, use { … } to tell the parser that they're one single compound command.

content-generator |
{ echo START; cat; echo END; } |
postprocessor

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.