Reputation: 1471
Dear Stackoverflow and Perl comrades:
I have a little question about Perl: I'm writing a log reader. The log format is like this
2013-05-27T19:01:23 [INFO] item_id:1, state:start at Reader.pm line 23
2013-05-27T19:01:29 [INFO] item_id:2, state:pause at Reader.pm line 23
2013-05-27T19:01:30 [INFO] item_id:1, state:start at Reader.pm line 23
...
My goal is to count how many state:start a given item_id, for example, item_id:1, shows. In this case, it should be 2.
So far what I have thought about is a counter of words:
sub count {
my $count_start = 0;
open (MYFILE, $file_location) or die "Wrong filename";
while ($file_location = <MYFILE>){
while ($file_location =~ /\bstart\b/ig){
$count_start++;
}
}
close (MYFILE);
return $count_start;
}
But I have to count not how many times "start" appears but how many times "start" and "id" appear in the same line. I know I have to add some regular expression but cant figure out anything. Any ideas?
Regards!
Upvotes: 1
Views: 154
Reputation: 385645
Assuming the order of the field is predictable:
my %counts;
while (<>) {
++$counts{$1} if /item_id:(\S+), state:start/;
}
Upvotes: 2
Reputation: 4553
A nasty one-liner for you:
mogul@guldager:~/tmp$ perl -MData::Dumper -ne '$h{$1}++ if /(\d+), state:start/;END{print Dumper \%h}'<input-data.txt
$VAR1 = {
'1' => 2
};
Upvotes: -1