perl - Extract the string in each line in a text file and count the occurrence of that string in the file -


i have log file sample output below. want extract value of string starting k= in each line using perl , count frequency of string in full log file.

threaddistributor dispatch k='/678605358297;type=f', i=2 threaddistributor dispatch k='/678605358297;type=w', i=0 threaddistributor dispatch k='/678605358297;type=w', i=1 

expected result:

k='/678605358297;type=f' occurs 1 times k='/678605358297;type=w' occurs 2 times 

this have tried far:

use test::more qw(no_plan);  use strict; use warnings; use data::dumper; $data::dumper::sortkeys=1; @key; @keystrings;  open (infile, "1.txt") or die "error:cannot open test result file $!"; foreach $line (<infile>) {      @key = split(' ',$line);     push @keystrings, $key[2]  }  print "$key[2]\n";   %counts; $counts{$_}++ @keystrings; print dumper(\%counts);  close infile; 

use regular expression grab string care about, , hash count occurrences. save following count.pl:

#!/usr/bin/env perl use strict; use warnings;  $leader = 'threaddistributor dispatch'; %dispatch_types; while (<>) {     chomp;     next unless m|^$leader|; # ignore else     ($type) = m|^$leader (k=\'.+?\'),|;     defined $type         or die "invalid row : '$_'";     # print "type $type\n";     $dispatch_types{$type}++; }  $type ( sort keys %dispatch_types ) {     print "$type occurs " . $dispatch_types{$type} . " times\n"; } 

and run as:

cat my_log_file | count.pl  k='/678605358297;type=f' occurs 1 times k='/678605358297;type=w' occurs 2 times 

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -