0

(I am looking for a better solution in Perl for this problem).

Here is the abstract of the goal: I have a file output.txt, it contains Unexpected exception : which is followed by different exceptions... For instance, it looks like

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

Here is a Perl script which summarizes output.txt by listing what exceptions are raised and their number of occurrence:

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

The result looks like:

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

Now I would like to improve this script, so that the exceptions could be listed in an alphabetical order:

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

Does anyone know how to change this script to achieve this goal?

Additionally, I may want to list the exceptions in a decreasing order of the occurrence:

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

Does anyone know to do it?

3
  • 2
    just do all that stuff | sort Commented Feb 28, 2014 at 8:01
  • @RedCricket that is cool... it answers to my first question... Do you have an idea for the second one? Commented Feb 28, 2014 at 8:08
  • man sort will answer your question. Commented Feb 28, 2014 at 8:12

3 Answers 3

2

Sort by exception name

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

Sort by occurances

perl -lne '$keys{$2}++ if (/^(Unexpected exception) : (.*?)\s*$/); END { for $i (sort { $keys{$b} <=> $keys{$a} } keys %keys) { print "   ", $i, " ", $keys{$i} } }' $1
Sign up to request clarification or add additional context in comments.

Comments

1

I hope this script-version is more readable:

#!/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

Comments

0

Perl/sort/uniq solution. Strip the leading text, sort, then count:

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

To sort by number of occurrences, add an extra sort -g:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.