Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: get n lines before or after a pattern

by brx (Pilgrim)
on Jul 26, 2012 at 17:09 UTC ( #983879=note: print w/replies, xml ) Need Help??

in reply to get n lines before or after a pattern

Similar to zentara's approach in Re: get n lines before or after a pattern.
The idea is to keep it short, to be independent of other lines content, to deal with file boundaries (ie to find 'jack' in firsts or lasts lines is OK).

note: the program could print the same line several times if 'jack' is found in consecutive lines - does OP want that?

#!perl use strict; use warnings; my @buffer=("")x6; my $line; while (@buffer) { push @buffer,$line if defined($line=scalar(<DATA>)); shift @buffer; print @buffer[0,1,2],$buffer[5]//'' if ($buffer[2]//'')=~/\bjack\b +/; #match index: ^ ^ } __DATA__ extra jack extra extra start id 10 address Richmond name jack xxxxx aaaaa lastname black yyyy zzzzz id 11 address Central name rick cccccc dddddd lastname hanna eeeee yyyyy id 12 address denver name jack sssss tttttt lastname strong rrrrr mmmmm id 13 address Virginia name mick aaaaaaa ooooooo lastname jagger gggggg hhhhhh id 14 address Maine name rick sssss sssss lastname stewart ssssss ffffff end extra extra jack
English is not my mother tongue.
Les tongues de ma mère sont "made in France".

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://983879]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2018-07-19 21:45 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (420 votes). Check out past polls.