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

前端 未结 3 489
逝去的感伤
逝去的感伤 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:26

    To do this job robustly you need:

    $ cat tst.awk
    BEGIN { FS="," }
    !($1 in max) {
        max[$1]  = $3
        data[$1] = $0
        keys[++numKeys] = $1
    }
    $3 > max[$1] {
        max[$1]  = $3
        data[$1] = $0
    }
    END {
        for (keyNr=1; keyNr<=numKeys; keyNr++) {
            print data[keys[keyNr]]
        }
    }
    
    $ awk -f tst.awk file
    item1,12:45,50,55
    item2,12:15,30,45
    item3,23:00,40,44
    

    When doing min/max calculations you should always seed your min/max value with the first value read rather than assuming it'll always be less than or greater than some arbitrary value (e.g. zero-or-null if you skip the !($1 in max) block above).

    You need the keys array to preserve input order when printing the output. If you use in instead then the output order will be random.

    Note that idiomatic awk syntax is simply:

     {  }
    

    not C-style:

    { if (  ) {  } }
    

提交回复
热议问题