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

Re: get n lines before a pattern

by VinsWorldcom (Priest)
on Jul 25, 2012 at 14:43 UTC ( #983673=note: print w/ replies, xml ) Need Help??


in reply to get n lines before or after a pattern

Note you're output is not only showing 2 lines before the pattern, but also 1 line AFTER the pattern.

You don't need Perl for something that simple:

grep -B2 -A1 jack test.txt

UPDATE: Since the OP updated the original question, this approach is no longer valid. See my reply (Re^3: get n lines before a pattern) below.


Comment on Re: get n lines before a pattern
Download Code
Re^2: get n lines before a pattern
by darklord_999 (Acolyte) on Jul 25, 2012 at 14:55 UTC
    I have updated the details of my file. Please see the change . Sorry for the previous error.

      Yes, the changes to the file in the OP certainly require an updated approach. What have you tried?

      I would loop through the file saving each key and either pushing to a data structure if the name matches or resetting and continuing.

      Pseudo code for the loop and structure I'd use:

      my @matches; my $FOUND = 0; my %info = {}; while (<INFILE>) { chomp $_; if (($_ =~ /^id/) and ($FOUND)) { push @matches \%info; $FOUND = 0; %info = {} } if ($_ =~ /^id/) { (undef, $info{id}) = split / /, $_} if ($_ =~ /^address/) { (undef, $info{address}) = split / /, $_} if ($_ =~ /^name/) { (undef, $info{fname}) = split / /, $_} ... if ($searchPattern eq $info{fname}) { $FOUND = 1; } }

      UPDATE: Added 'chomp' and updated 'split' commands as per kennethk suggestions to me.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (10)
As of 2014-09-19 09:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (134 votes), past polls