Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Generate number of occurances of each item in a list.

0 views
Skip to first unread message

Dave

unread,
Sep 30, 2008, 11:19:14 AM9/30/08
to
I've got a list of user names (see below) of opponents of mine on a
chess server. I'd list to find the number of occurances of each opponent
and sort them in order, so I can find the most frequent opponents.

i.e from this list

papajack
Toalla
ourma
ourma
ChuckRobbins
ChuckRobbins
patrick41
patrick41
Velocity
Velocity
Velocity
Velocity
Velocity
maximosz
maximosz
maximosz
Toalla

get:

5 Velocity
3 maximosz
2 patrick41
2 ourma
2 Toalla
2 ChuckRobbins
1 papajack


The original list are not sorted - Toalla for instance if at the top and
bottom, but of course sorting them would be trivual.

Any thoughts? Is this something a perl guru can do, or do I need to
write some C code?

The number of usernames in the list is around 4000, so efficiency is not
going to be a major concern. Any have decent solution should be able to
work on 4000 without much difficulty.

Michael Schindler

unread,
Sep 30, 2008, 11:36:08 AM9/30/08
to
Dave wrote:

try this:

cat << EOF | \
awk ' { arr[$1]++ }
END { for (Name in arr)
{
printf "%d\t%s\n", arr[Name], Name;
}}' | sort -rn


papajack
Toalla
ourma
ourma
ChuckRobbins
ChuckRobbins
patrick41
patrick41
Velocity
Velocity
Velocity
Velocity
Velocity
maximosz
maximosz
maximosz
Toalla

EOF

Stephane CHAZELAS

unread,
Sep 30, 2008, 11:50:35 AM9/30/08
to
2008-09-30, 16:19(+01), Dave:

> I've got a list of user names (see below) of opponents of mine on a
> chess server. I'd list to find the number of occurances of each opponent
> and sort them in order, so I can find the most frequent opponents.
[...]

sort | uniq -c | sort -rn

--
Stéphane

Ed Morton

unread,
Sep 30, 2008, 11:53:41 AM9/30/08
to

sort file | uniq -c | sort -rn

Ed.

John W. Krahn

unread,
Sep 30, 2008, 3:10:08 PM9/30/08
to

perl -lne'++$x{$_}}{print"$x{$_}\t$_"for sort{$x{$b}<=>$x{$a}}keys%x'
yourfile

John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall

Dave

unread,
Oct 4, 2008, 4:28:58 AM10/4/08
to

Thank you everyone who replied. Clearly

sort filename | uniq -c | sort -rn

is much easier than some of the other solutions.

Dave

0 new messages