In the given data is it possible to uniq sort and print only the top hits against each region?

Given Data

aza1 18
bcn1 16
sat2 12
lcy2 12
fra1 12
aza1 12
bcn1 10
sat2 8
lcy2 9
fra1 13
aza1 21
bcn1 2
sat2 10
lcy2 0
fra1 1

Required Output

aza1 21
bcn1 16
sat2 12
lcy2 12
fra1 13
  • 1
    Is the order important? it's easier to do if the first column can be in lexical order – steeldriver Apr 17 '19 at 17:58

Solution if order matters, using only sort and uniq

<INPUT_FILE sort -k 1,1 -k 2nr,2 | uniq -w4


aza1 21
bcn1 16
fra1 13
lcy2 12
sat2 12

Sort parameters:

-k: sort by key (in this case column, pairs with -t)

-n: sort as a number

-r: reverse order

(optional) -t: in case you want to change the key separator (default: space)

Uniq parameter:

-w: choose the first N characters


In your problem, we need to first sort the first column and then the second one. So there is a -k 1,1 followed by -k 2,2. But, the second key (ONLY) must be sorted as a number and in the reverse order. Thus, it should be -k 2nr,2.

Note that if the -n or -r sort parameters are outside -k parameter, they are applied to the whole input instead of specific keys.

Lastly, me must find the unique lines, but matching only the first 4 chars. Thus, uniq -w 4


If the order doesn't matter:

<infile sort -rnk2,2  |sort -uk1,1

-revers -numerical sort on -key column number 2 (sort -rnk2,2), then keep and -unique lines on first -key column (sort -uk1,1);

or same with awk:

<infile awk '
            { arr[$1]= (arr[$1]<$2)? $2 : arr[$1] }
         END{ for (x in arr) print x, arr[x] }'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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