For Programmers: Free Programming Magazines  


Home > Archive > AWK > October 2004 > Re: printing a range of lines only if subsequent records contain









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re: printing a range of lines only if subsequent records contain
Janis Papanagnou

2004-10-13, 8:55 pm

entropic wrote:
> I'd like to print a range of lines from multiple files. The printout
> should have the filename and, then, print out a range of records from
> line n-2 to n+1 of every file only if:
>
> 1. the record n contains pattern 'foo', and
> 2. record n+1 contains pattern 'bar', then
> 3. exit and read subsequent file.
>
> I know I should read in subsequent records into an array and then do
> the comparison, but the exact syntax evades me...


You don't need an array, since your offsets are small and constant,
something like the following code should do it...

/bar/ { if (flag) { print h2 ; print h1 ; print h0 ; print $0 ; nextfile } }
{ flag = 0; h2 = h1 ; h1 = h0 ; h0 = $0 }
/foo/ { flag = 1 }

Be aware that 'nextfile' is a gawk feature, if you don't have gawk use
'exit' and either feed the files separately to your script or implement
another state flag.

Janis
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com