有一大堆日誌,需要按裝置統計一下各個裝置中日誌記錄中返回碼的個數。
裝置名稱字可以根據檔案名稱字獲得, 日誌記錄是有一定格式的。第七個欄位是 返回碼。
分別shell和perl實現了,Perl不熟,網上拼了個代碼。
use Text::ParseWords;<br />use Data::Dumper;<br />my $result;<br />my %table;<br />$argv_len = @ARGV;<br />if($argv_len == 0)<br />{<br /> print "it need filename/n";<br /> exit(1);<br />}<br />$cmd="ls '".join("' '",@ARGV)."' |";</p><p>open(PIPE, $cmd);<br />@filenames = <PIPE>;<br />close(PIPE);</p><p>foreach(@filenames){<br /> analy($_);<br />}</p><p>sub trim<br />{<br /> my $string = shift;<br /> $string =~ s/^/s+//;<br /> $string =~ s//s+$//;<br /> return $string;<br />}</p><p>sub analy<br />{<br /> my $filename= trim(shift);<br /> $cmd="cat $filename |";<br /> open(PIPEFILE,$cmd);<br /> @lines=<PIPEFILE>;<br /> close(PIPEFILE);<br /> my ($sn,$dev_id,$time) = split(/_/g,$filename);<br /> my $dev=$dev_id.'-'.substr($sn,-3);</p><p> my %code;<br /> foreach(@lines)<br /> {<br /> my @line=quotewords(" ", 1, $_);<br /> $code{$line[7]}++;<br /> }<br /> $table{$dev} = [] unless exists $table{$dev};<br /> push @{$table{$dev}}, /%code;<br />}<br />foreach my $dev(sort keys %table) {<br /> print "$dev:/n ";<br /> my @code = @{$table{$dev}};<br /> foreach my $code(@code)<br /> {<br /> foreach my $key(keys(%{$code}))<br /> {<br /> $result{$key}+= $code->{$key};<br /> }<br /> }<br /> print "keys /t/t values/n";<br /> foreach my $value (keys(%result))<br /> {<br /> print $value." /t/t".$result{$value};<br /> print "./n";<br /> }<br />}
使用shell就比較簡單了,只有幾行:
#!/bin/sh<br />while read line<br />do<br />echo $line<br /> grep HTTP /path/20110527/ -r | grep $line | awk '{a[$10]++} END {for(i in a) print i " "a[i]}'<br />done < dev_list