Perl:匹配模式后如何打印下一行? [英] Perl: How to print next line after matching a pattern?
本文介绍了Perl:匹配模式后如何打印下一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在匹配模式或线条后打印特定数据.我有一个这样的文件:
I would like to print specific data after matching a pattern or line. I have a file like this:
#******************************
List : car
Design: S
Date: Sun 10:10
#******************************
b-black
g-green
r-red
Car Type No. color
#-------------------------------------------
N17 bg099 g
#-------------------------------------------
Total 1 car
#******************************
List : car
Design: L
Date: Sun 10:20
#******************************
b-black
g-green
r-red
Car Type No. color
#-------------------------------------------
A57 ft2233 b
#-------------------------------------------
Total 1 car
#******************************
List : car
Design: M
Date: Sun 12:10
#******************************
b-black
g-green
r-red
Car Type No. color
#-------------------------------------------
L45 nh669 g
#-------------------------------------------
Total 1 car
#. .
#. .
#.
#.
我想打印数据,例如在Type...."行和虚线------"之后打印数据,即 N17 和 bg099.我试过这个,但它不能工作.
I want to print the data for example after the lines "Type...." and dashes line"------" which is N17 and bg099. I have tried this but it cannot work.
my @array;
While (@array = <FILE>) {
foreach my $line (@array) {
if ($line =~ m/(Car)((.*))/) {
my $a = $array[$i+2];
push (@array, $a);
}
if ($array[$i+2] =~ m/(.*)\s+(.*)\s+(.*)/) {
my $car_type = "$1";
print "$car_type\n";
}
}
}
预期输出:
Car Type No.
N17 bg099
A57 ft2233
L45 nh669
.. ..
. .
推荐答案
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";
}
}
这篇关于Perl:匹配模式后如何打印下一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文