http://www.perlmonks.org?node_id=338884

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I have this file I am reading which contains the following:
817 5:00 817 5:00 817 5:15 123 4:45 817 5:30 495 7:45
I am trying to count the occurrence of each location so for the file listed above I should have output as follow:
817=4 123=1 495=1
Any Idea of an easy way to do it? Thanks

Replies are listed 'Best First'.
Re: count of a word occurrence
by jZed (Prior) on Mar 23, 2004 at 04:17 UTC
    my %hash; for (<DATA>) { s/^(\S+).*/$1/; $hash{$_}++ } use Data::Dumper; print Dumper \%hash; __DATA__ 817 5:00 817 5:00 817 5:15 123 4:45 817 5:30 495 7:45

      Same thing, just slightly shorter (and maybe clearer):

      #! /usr/bin/perl use strict; use Data::Dumper; my %hash; /^(\d+).*/ and $hash{$1}++ for <DATA>; print Dumper \%hash; __DATA__ 817 5:00 817 5:00 817 5:15 123 4:45 817 5:30 495 7:45

      _______________
      DamnDirtyApe
      Those who know that they are profound strive for clarity. Those who
      would like to seem profound to the crowd strive for obscurity.
                  --Friedrich Nietzsche
        Death to dot-star! (It's useless in your example, and in jZed's.)

        The PerlMonk tr/// Advocate
Re: count of a word occurrence
by sgifford (Prior) on Mar 23, 2004 at 06:22 UTC
    Golfed solution:
    perl -lane '$c{$F[0]}++;END{print"$_=$c{$_}"for keys%c}'
Re: count of a word occurrence
by chimni (Pilgrim) on Mar 23, 2004 at 04:15 UTC

    1) read the file in a while loop,split and use a hash ($hash{$_}++ ).
    2) use someting like the below for all unique entries in the first column.
    grep 817 filename | wc -l
    hth
    chimni
      That won't quite get it. Do
      cut -f1 filename | sort | uniq -c

      jdporter
      The 6th Rule of Perl Club is -- There is no Rule #6.