Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it's not printing the maximum score of individual player?

Tags:

bash

shell

awk

I want to use the awk utility to list the maximum score of individual player.

This is my cricketer.txt file:

Virat Kohli:30
Suresh Raina:90
Shikhar Dhawan:122
Virat Kohli:33
Shikhar Dhawan:39
Suresh Raina:10
Suresh Raina:44
MS Dhoni:101
MS Dhoni:33
Virat Kohli:39
Virat Kohli:93
Virat Kohli:94
Steven Smith:44
Steven Smith:32
Rohit Sharma:33
Rohit Sharma:18
Rohit Sharma:206
Steven Smith:55

This is my max.awk file:

awk -F ":" -v c=0 '{name[c]=$1;runs[c]=$2;c++;}
END{
i=0
j=0
while(i<NR)
{
    j=0
    k=0
    k1=0
    max=0
    while(j<NR)
    {
        if(name[i]==name[j])
        {
        cruns[k]=runs[j]
        k++
        }
        max=cruns[0]
        if(cruns[k1] > max)     
        {
            max=cruns[k1]
            k1=k1+1
        }
        j=j+1           
    }
    print name[i],max
    i=i+1
  }
}' cricketer.txt | sort | uniq > max.txt

This is my max.txt file I am getting.

MS Dhoni 101
Rohit Sharma 33
Shikhar Dhawan 122
Steven Smith 44
Suresh Raina 90
Virat Kohli 30

It looks like that it is printing only the first score of each individual player. Is the code of max.awk file is wrong?

like image 847
Parth Mangukiya Avatar asked Mar 16 '18 03:03

Parth Mangukiya


2 Answers

Following awk may help you on same, to get the maximum score for each cricketer :)

awk -F":" '{a[$1]=a[$1]>$NF?a[$1]:$NF} END{for(i in a){print i,a[i]}}' Input_file
like image 54
RavinderSingh13 Avatar answered Sep 18 '22 04:09

RavinderSingh13


$ sort -t: -k2rn file | awk -F':' '!seen[$1]++'
Rohit Sharma:206
Shikhar Dhawan:122
MS Dhoni:101
Virat Kohli:94
Suresh Raina:90
Steven Smith:55
like image 29
Ed Morton Avatar answered Sep 20 '22 04:09

Ed Morton