Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

count of a word occurrence

by Anonymous Monk
on Mar 23, 2004 at 04:00 UTC ( #338884=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://338884]
Approved by kvale
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2021-12-03 23:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    R or B?



    Results (30 votes). Check out past polls.

    Notices?