Perl读取所有计数的日志

时间:2011-02-23 08:59:15

标签: perl

我正在尝试使用Perl读取日志文件,

我有大约500行,类似

timestamp, amount1, amount2, amount3
12334        20         0       0
12335        0         20       0
12335        0         20       20
12336        0         20       0
12336        0         20       20

我希望输出为

12334 20  0   0
12335  0  40  20
12336  0  40  20

如何获得这种输出?

2 个答案:

答案 0 :(得分:3)

您可以使用哈希来汇总每个时间戳的数据,如下所示:

# skip header
my $header = <DATA>;

# read data into a hash
my %summary =();
while(<DATA>) {
    chomp;
    my ($timestamp, @amounts) = split;
    for my $i (0..$#amounts) {
        $summary{$timestamp} ||= [];
        $summary{$timestamp}[$i] += $amounts[$i];
    }
}

# print out the summary
for my $timestamp (sort { $a <=> $b } keys %summary) {
    print $timestamp,"  ",join("  ",@{ $summary{$timestamp} }),"\n";
}

__DATA__
timestamp, amount1, amount2, amount3
12334        20         0       0
12335        0         20       0
12335        0         20       20
12336        0         20       0
12336        0         20       20

当然,如果您的数据更复杂,您应该使用适当的解析器(如Text::xSV)来处理数据。

答案 1 :(得分:2)

%myHash = ();

while (<>) {
   my ($ts,$a1,$a2,$a3) = split;
   # Put into hash by ts-value
   if (exists $myHash{$ts}) {
      $myHash{$ts}{amount1} = $myHash{$ts}{amount1} + $a1;
      $myHash{$ts}{amount2} = $myHash{$ts}{amount2} + $a2;
      $myHash{$ts}{amount3} = $myHash{$ts}{amount3} + $a3;
   }
   else {
      $myHash{$ts}{amount1} = $a1;
      $myHash{$ts}{amount2} = $a2;
      $myHash{$ts}{amount3} = $a3;
   }    
}

然后只需浏览哈希的键并打印出来

foreach (keys %myHash) {
   printf("%5d %3d %3d %3d\n", $_, $myHash{$_}{amount1}, $myHash{$_}{amount2}, $myHash{$_}{amount3});
}

或类似的东西......我还没有完成它,但这样的事情,我相信你想要的是什么?