RAJ
RAJ

Reputation: 21

Perl loopproblem when checking for pattern in current and next line

i have a file something like this

1 XXXX jimmy XXXXX XXXXX
2 XXXX johny XXXXX XXXXX
3 XXXX jimmy XXXXX XXXXX
4 XXXX jimmy XXXXX XXXXX
5 XXXX johny XXXXX XXXXX

I would like to loop through the file and print line only if current line is having jimmy with a consecutive line having johny

I have written code to check for the next line if current line matches with the pattern but the coding is not looping through every line for example i am getting

output for above file as

1 XXXX jimmy XXXXX XXXXX
2 XXXX johny XXXXX XXXXX

following is part of my code

while($line=<ABC>){
    $c1=(split (/\s+/, $line))[1];
    if($c1 eq 'jimmy'){
        $i=0;
        while ($i<1){
            $line2 = <ABC> ;
            $i++;
            $c12=(split (/\s+/, $line2))[1];
            if($c12 eq 'johny') {
                print $line."\n".$line2."\n";
            }

Upvotes: 2

Views: 88

Answers (1)

Chankey Pathak
Chankey Pathak

Reputation: 21666

#!/usr/bin/perl
use strict;
use warnings;
my $ln;
while(my $line = <DATA>){
    if($ln && $ln =~ /jimmy/ && $line =~ /johny/){
        #print whatever you need to
        print "ln is: $ln line is $line";
    }
    $ln = $line;
}
__DATA__
1 XXXX jimmy XXXXX XXXXX
2 XXXX johny XXXXX XXXXX
3 XXXX jimmy XXXXX XXXXX
4 XXXX jimmy XXXXX XXXXX
5 XXXX johny XXXXX XXXXX

Demo

Upvotes: 3

Related Questions