awk group by multiple columns and print max value with non-primary key

前端 未结 3 582
逝去的感伤
逝去的感伤 2021-01-21 10:29

i\'m new to this site and trying to learn awk. i\'m trying to find the maximum value of field3, grouping by field1 and print all the fields with maximum value. Field 2 contains

3条回答
  •  不要未来只要你来
    2021-01-21 11:24

    The problem here is that you are not storing the whole line, so when you go through the final data there is no full data to print.

    What you need to do is to use another array, say data[index]=full line:

    BEGIN{
    FS=OFS=","}
    {
     if (a[$1]<$3){
       a[$1]=$3
       data[$1]=$0}       # store it here!
    }
    END {
       for (i in a )
           print data[i]  # print it here
    }
    

    Or as a one-liner:

    $ awk 'BEGIN{FS=OFS=","} {if (a[$1]<$3) {a[$1]=$3; data[$1]=$0}} END{for (i in a) print data[i]}' file
    item1,12:45,50,55
    item2,12:15,30,45
    item3,23:00,40,44
    

提交回复
热议问题