Parth Mangukiya
Parth Mangukiya

Reputation: 454

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

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?

Upvotes: 5

Views: 107

Answers (2)

Ed Morton
Ed Morton

Reputation: 203655

$ 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

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133528

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

Upvotes: 5

Related Questions