Zoe*_*Zoe 3 perl pattern-matching
我想在匹配图案或线后打印特定数据.我有这样一个文件:
#******************************
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
#. .
#. .
#.
#.
Run Code Online (Sandbox Code Playgroud)
我想打印数据,例如在"Type ...."行后面,并用"------"作为N17和bg099.我试过这个,但它无法正常工作.
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";
}
}
}
Run Code Online (Sandbox Code Playgroud)
预期产出:
Car Type No.
N17 bg099
A57 ft2233
L45 nh669
.. ..
. .
Run Code Online (Sandbox Code Playgroud)
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";
}
}
Run Code Online (Sandbox Code Playgroud)
或者如果您更喜欢更紧凑的解决方案:
while (<FILE>) {
if ($_ =~ /^Car/) {
<FILE> or die "Bad car file format";
print join(" ",(<FILE> =~ /(\w+)\s+(\w+)/))."\n";
}
}
Run Code Online (Sandbox Code Playgroud)