http://www.perlmonks.org?node_id=983676


in reply to Re: get n lines before a pattern
in thread get n lines before or after a pattern

I have updated the details of my file. Please see the change . Sorry for the previous error.

Replies are listed 'Best First'.
Re^3: get n lines before a pattern
by VinsWorldcom (Prior) on Jul 25, 2012 at 15:16 UTC

    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.