in reply to grab 'n' lines from a file above and below a /match/

Well, you'll have to store the lines. And it's going to be tricky to correctly handle matches where the context overlaps, ie where one match follows less than 2n lines from the previous.

The easiest thing to do is use the toolbox: egrep -C n c9391b56-b174-441b-921c-7d63 GWSvc.log

Update: the following should work and handle all edge cases:

my @backlog; my $to_print = 0; my $context_size = 10; while(<>) { $to_print = 1 + $context_size if /c9391b56-b174-441b-921c-7d63/; push @backlog, $_; if( $to_print ) { print shift @backlog; --$to_print; } elsif( @backlog > $context_size / 2 ) { shift @backlog; } } print shift @backlog while @backlog and $to_print--;

Makeshifts last the longest.

Replies are listed 'Best First'.
Re^2: grab 'n' lines from a file above and below a /match/
by tachyon (Chancellor) on Sep 17, 2004 at 03:55 UTC

    TIMTOWDI or here is one way to use $. ;-)

    my $context = 4; my @buffer = ('') x $context; my $print_to = 0; my $match = qr/42/; while(<DATA>) { if ( m/$match/ ) { print @buffer; $print_to = $. + $context; @buffer = ('') x $context; } push @buffer,$_; shift @buffer; print if $. <= $print_to; }

    cheers

    tachyon

Re^2: grab 'n' lines from a file above and below a /match/
by barathbr (Scribe) on Sep 16, 2004 at 22:50 UTC
    I have the gateway running at full logging level, thats the only time I am going to be seeing these params (this particular one is actually a SIP subscribe request ID, additional parts of which I have removed). I will be running into such entries probably once in 100 lines. So, I am not really worried about the overlap part of your answer.

    As for egrep - its windows, so not available to me - plz help
        Maybe even pcregrep has a windows port? I'm too lazy to check though.
Re^2: grab 'n' lines from a file above and below a /match/
by barathbr (Scribe) on Sep 16, 2004 at 23:29 UTC
    Hey, On a lighter note - I now realize that I was operating on $_ and trying to play with $., what I dont understand is where would I use $. -> any typical situations where $. might come in handy
    you might find this to be a newbie question, but I am still learning perl and am just curious.
    thanks again

      $. is just the number of the last line read from the last accessed filehandle. It's useful any time you want to know the line number. It does nothing beyond that; in particular, writing to it has no effect at all, other than that its value changes.

      Makeshifts last the longest.

Re^2: grab 'n' lines from a file above and below a /match/
by barathbr (Scribe) on Sep 16, 2004 at 23:15 UTC
    Hey this works too !!
    thanks a lot