pogibas
pogibas

Reputation: 28339

awk array: print fields after selecting arrays element

I have used awk command to extract maximum value from the dummy file.

cat dummy_file

    Cat Felix 3
    Cat Garfield 2
    Cat Tom 1
    Dog Snoopy 5
    Dog Spike 4


awk '{max[$1] =!($1 in max) ? $3 : ($3 > max[$1]) ? $3 : max[$1]} \  
    END {for (i in max) print i,max[i]}' dummy_file

    Cat 3
    Dog 5

Additionally to extracted maximum value and arrays element I need corresponding $2. For the output like this:

    Cat Felix 3
    Dog Snoopy 5

My question is - how to print wanted field after selecting arrays element?

Upvotes: 1

Views: 177

Answers (1)

Håkon Hægland
Håkon Hægland

Reputation: 40748

You can try:

{
    if ($1 in max) {
        if ($3> max[$1]) {
            max[$1]=$3
            type[$1]=$2
        }
    } else {
        max[$1] = $3
        type[$1]=$2
    }
}
END {
    for (i in max) print i,type[i],max[i]
}

Upvotes: 1

Related Questions