18

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 
1

4 Answers 4

27

This works, as indicated by jasonwryan:

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

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

Warning: the question says “I have a bunch of output ...”  If you run the above command with no data, you will get no output, because the command depends on there actually being a first line and a last line.  The other two answers will give the header and footer even if the input is null.

12

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 
1
1
sed -e '1s/.*/START\n&/g' -e '$s/.*/&\nEND/g' filename START All this code on all these lines and all these END 

Python

#!/usr/bin/python k=open('filename','r') o=k.readlines() for i in range(0,len(o),1): if ( i == 0 ): print "START" print o[i].strip() elif ( i == (len(o)-1)): print o[i].strip() print "END" else: print o[i].strip() 

output

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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.