2014-02-28 50 views
0

(我正在尋找Perl的更好解決方案,用於this problem)。對perl中的輸出(數組)進行排序

這裏是目標的摘要:我有一個文件output.txt,它包含Unexpected exception :後面是不同的例外......舉例來說,它看起來像

... 
Unexpected exception : exception1 
... 
Unexpected exception : exception2 
... 

這裏是一個Perl腳本,總結output.txt通過列出上調異常是什麼及其發生的數量:

perl -lne '$a{$2}++ if (/^(Unexpected exception) : (.*?)\s*$/); END { for $i (keys %a) { print " ", $i, " ", $a{$i} } }' $1 

結果是這樣的:

exception2 : 15 
exception3 : 7 
exception1 : 9 
... 

現在我想改善這個腳本,這樣異常可以按字母順序排列:

exception1 : 9 
exception2 : 15 
exception3 : 7 
... 

有誰知道如何改變這個腳本來實現這一目標?

此外,我可能要列出例外發生的遞減順序:

exception15 : 20 
exception2 : 15 
exception1 : 9 
exception3 : 7 
... 

有誰知道該怎麼辦呢?

+2

只是做'所有的東西|排序' –

+0

@RedCricket很酷......它回答我的第一個問題......你有第二個想法嗎? – SoftTimur

+0

'人排序'將回答你的問題。 –

回答

2

排序異常名

perl -lne '$a{$2}++ if (/^(Unexpected exception) : (.*?)\s*$/); END { for $i (sort keys %a) { print " ", $i, " ", $a{$i} } }' $1 

排序occurances

perl -lne '$keys{$2}++ if (/^(Unexpected exception) : (.*?)\s*$/); END { for $i (sort { $keys{$b} <=> $keys{$a} } keys %keys) { print " ", $i, " ", $keys{$i} } }' $1 
1

我希望這個腳本的版本更具可讀性:

#!/usr/bin/perl 

use warnings; 
use strict; 

my %exceptions; 

while (<DATA>) { 
    chomp; 
    $exceptions{$1}++ if (m/^Unexpected exception : (.*?)\s*$/); 
} 

print "Sorted by exception name:\n"; 
foreach my $exc (sort keys %exceptions) { 
    print "$exc : $exceptions{$exc}\n"; 
} 

print "Sorted by exception count:\n"; 
foreach my $exc (sort { $exceptions{$b} <=> $exceptions{$a} } keys %exceptions) { 
    print "$exc : $exceptions{$exc}\n"; 
} 

__DATA__ 
Unexpected exception : exception1 
Unexpected exception : exception2 
Unexpected exception : exception2 
0

的Perl /排序/ uniq的解決方案。剝去領先的文字,排序,再算上:

perl -pe 's/Unexpected exception : //' input.txt | sort | uniq -c 

爲按次數進行排序,添加一個額外的sort -g

perl -pe 's/Unexpected exception : //' input.txt | sort | uniq -c | sort -g