Saturday, June 27, 2009

Print last section using awk RS variable


This post is mainly intended for the awk newbies.
Input file:

$ cat grn.log
Sat Jun 27 20:56:36 IST 2009 : Init
Sat Jun 27 20:56:39 IST 2009 : Phase1,mval=45
Sat Jun 27 20:56:46 IST 2009 : End
---
Sat Jun 27 21:06:15 IST 2009 : Phase1.4
Sat Jun 27 21:06:39 IST 2009 : Phase4,kval=23
Sat Jun 27 21:06:59 IST 2009 : Phase5,kval=29
Sat Jun 27 21:07:36 IST 2009 : End
---
Sat Jun 27 21:15:36 IST 2009 : Init
Sat Jun 27 21:16:29 IST 2009 : Phase1,mval=42
Sat Jun 27 21:16:46 IST 2009 : Cont

Output Required: Print the last section of the above file.

In general AWK reads one line at a time, and breaks up the line into fields.
We can print the last line this way:

$ awk 'END{print}' grn.log

o/p:
Sat Jun 27 21:16:46 IST 2009 : Cont

Now setting awk RS variable to "---", we can tell awk to treat a whole section as a line and then we can print the last section in the same way as above.


$ awk 'BEGIN{RS="---"}END{print}' grn.log

o/p:
Sat Jun 27 21:15:36 IST 2009 : Init
Sat Jun 27 21:16:29 IST 2009 : Phase1,mval=42
Sat Jun 27 21:16:46 IST 2009 : Cont

2 comments:

C1c4Tr1Z said...

offcommand: or you could use tail.

~ $ tail -n 3 foobar.log
Sat Jun 27 21:15:36 IST 2009 : Init
Sat Jun 27 21:16:29 IST 2009 : Phase1,mval=42
Sat Jun 27 21:16:46 IST 2009 : Cont
~ $

Jadu Saikia said...

@C1c4Tr1Z, the problem in using tail here, if the length of a section is more or less to 3 (I mean num lines in one section is variable). Thanks for your comment.

© Jadu Saikia www.UNIXCL.com