![](/img/trans.png)
[英]Python - Print all log lines that match a pattern between 2 time stamps
[英]Read all the lines between a pattern match using Perl
我想读取一个csv文件。 csv文件如下所示,
cat,dog,0
apple,banana,0
#start_loop
jug,ball,0
tub, jar,3
#stop_loop
phone,bottle,10
#per head
#start_loop
cup,book,7
laptop,charger,9
#stop_loop
对于上面的csv,我想在#start和#stop之间阅读。 另外,我想区分两个#start_loop,例如,从第一个#start_loop到第一个数组的行和另一个#start_loop到另一个数组的行。
预期结果将是:
@array1 = {jug ball 0, tub jar 3}
和
@array2 = { cup book 7, laptop charger 9}
我该如何解决这个问题?
您可以使用触发器运算符。 #start行的值将为1,#stop行的值将包含E。
#!/usr/bin/perl
use warnings;
use strict;
my @arr;
while (<>) {
chomp;
my $inside = /^#start_loop/ .. /^#stop_loop/;
if ($inside) {
push @arr, [] if 1 == $inside;
undef $inside if 1 == $inside
|| $inside =~ /E/;
push @{ $arr[-1] }, $_ if $inside;
}
}
use Data::Dumper; print Dumper \@arr;
choroba解决方案的简化版本:
my @arr;
while (<>) {
chomp;
my $inside = /^#start_loop/ .. /^#stop_loop/;
if ( $inside == 1 ) { push @arr, []; } # Start line
elsif ( $inside !~ /E/ ) { push @{ $arr[-1] }, $_; } # Middle line
}
没有触发器:
my @arr;
my $inside;
while (<>) {
chomp;
if ( /^#start_loop/ ) { $inside = 1; push @arr, []; } # Start line
elsif ( /^#stop_loop/ ) { $inside = 0; } # Stop line
elsif ( $inside ) { push @{ $arr[-1] }, $_; } # Middle line
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.