List Counter

 
cat sport_by_month
 
Month : Jan
sport :Football
sport :Volleyball
Month: Feb
sport :BasketBall
sport: Cricket
sport: Fotball
Month: Mar 
Month: APR
sport : Bowling
sport : Climbing

I need your help to have a script that count the number of sports per month and sorted by mont with more sport, so my output would be something like

 
./count.sh
 
Feb  3
Jan 2
APR 1
Mar  0

Try:

awk '/Month/{m=$NF;A[m]=-1} {A[m]++} END{for(i in A)print i,A}' infile | sort -rnk2
awk '/Month/{if(NR>1)print m,c; m=$NF; c=-1}{c++} END{print m,c}' infile | sort -rnk2
1 Like

Hi,

Try this one,

awk '/^sport/{a[p]++;}/^Month/{gsub(/Month *: */,"");p=$0;a[p]="0";}END{for ( i in a){print i,a;}}' Input_File

Cheers,
Ranga:)

1 Like

In perl,

#!/usr/bin/perl
use Data::Dumper;

my %Hash = () ;
my ($fh , $mon , $name );
open $fh  ,"<file" or die "Can not open the file : $@";

while ( <$fh> ) {
     ($mon , $name ) = split ( ':',$_ ), chomp ( $name ) ,  $Hash{$name} = 0 , next   if ( /Month/ );
    $Hash{$name}++ if ( /sport/ ) ;
}

print Dumper \%Hash;
$
$ cat sport_by_month
Month : Jan
sport :Football
sport :Volleyball
Month: Feb
sport :BasketBall
sport: Cricket
sport: Fotball
Month: Mar
Month: APR
sport : Bowling
sport : Climbing
$
$
$ perl -lne '/^(\w+)\s*:\s*(\w+)$/;
             $1 eq "Month" ? do{$m=$2; $x{$m}=0} : $x{$m}++;
             END{print "$_  $x{$_}" for sort {$x{$a} <=> $x{$b}}(keys %x)}
            ' sport_by_month
Mar  0
Jan  2
APR  2
Feb  3
$
$

tyler_durden

Changing RS also does the trick.

$ awk 'NF>0{print $2,(gsub("\n",""))-1}' RS="Month" file
Jan 2
Feb 3
Mar 0
APR 2
$

Note: this works for gawk and mawk, but not the other awks. POSIX awk only accepts a single character for RS.

Ohk. I didn't know this. Thanks for pointing out.