Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (9)
As of 2017-12-15 09:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What programming language do you hate the most?




















    Results (425 votes). Check out past polls.

    Notices?