Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Live count of uniq lines

I've got a command that outputs a few different lines constantly (a stream), I'd like a live summary of the number of times each line has occurred (with a few seconds latency being acceptable).

for example if my command outputs the following:
apple
apple
apple
apple
banana
orange
banana

I'd like something like:
4 apple
2 banana
1 orange


and for the output to refresh every few seconds.

How might I achieve this? (rereading an entire log file will take too long, it has to be the output of a live pipe)
by

1 Answer

Amit8z4mc
Could be done with a short perl script like:
#! /usr/bin/perl
system qw(tput sc); # save cursor
$rc = `tput rc; tput ed`; # restore cursor and erase down
sub report {
print $rc;
print "$_: $c{$_}\n" for sort {
($c{$b} <=> $c{$a}) || ($a cmp $b)
} keys %c;
STDOUT->flush;
alarm 1;
}
$SIG{ALRM} = \&report;
alarm 1;
while (<>) {
chomp;
$c{$_}++;
}
report;

Login / Signup to Answer the Question.