Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a file with the following fields

NM001 rp1 210
NM003 rp1 220
NM005 rag 200
NM004 rag 100

I would like to have an output that for every change in column2, find maximum in column4 but also report corresponding column1. So far I found a solution that report column2 and 3 but not column1 because the number in column1 is different. I like to use awk please.

The output should be

NM003 rp1 220
NM005 rag 200
share|improve this question
You are closing up on the point where it will be easier to write something in perl or pyton. – Johan Jul 15 '11 at 7:50

You can do this quite easily with awk.

You need to keep track of the maximum value for each value in the second column, and you also want to keep the whole line for each which has the max value:

awk '
    $3 > maxvals[$2] {lines[$2]=$0; maxvals[$2]=$3}
    END { for (tag in lines) print lines[tag] }

The output is not sorted, so pipe into sort if you need a particular sorting.

share|improve this answer

Try with sort and uniq tools:

sort -k3,3nr infile |
awk '{ print $1" " $3" " $2 }' | 
uniq -f2 | awk '{ print $1" " $3" " $2 }' > outfile
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.