Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: get n lines before or after a pattern

by brx (Pilgrim)
on Jul 26, 2012 at 17:09 UTC ( [id://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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://983879]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2024-04-16 11:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found