Perl: How to print next line after matching a pattern?

后端 未结 7 1947
刺人心
刺人心 2021-01-06 15:52

I would like to print specific data after matching a pattern or line. I have a file like this:

#******************************    
List : car  
Design: S           


        
相关标签:
7条回答
  • 2021-01-06 16:19
    while (<FILE>) { #read line by line
        if ($_ =~ /^Car/) { #if the line starts with 'Car'
            <FILE> or die "Bad car file format"; #read the first line after a Car line, which is '---', in order to get to the next line
            my $model = <FILE>; #assign the second line after Car to $model, this is the line we're interested in.
    
            $model =~ /^([^\s]+)\s+([^\s]+)/; #no need for if, assuming correct file format #capture the first two words. You can replace [^\s] with \w, but I prefer the first option.
            print "$1 $2\n";
        }
    }
    

    Or if you prefer a more compact solution:

    while (<FILE>) { 
        if ($_ =~ /^Car/) { 
            <FILE> or die "Bad car file format"; 
            print join(" ",(<FILE> =~ /(\w+)\s+(\w+)/))."\n";
        } 
    } 
    
    0 讨论(0)
提交回复
热议问题