Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort lexicographically and numerically at the same time

Tags:

bash

sorting

I have a file tmp.txt (actually the output of a bash command) with entries like:

    ...
ammp            0                1.03683
ammp            10               2.69954
ammp            1                1.05712
ammp            11               2.70339
ammp            12               2.70339
ammp            2                1.88586
ammp            3                2.50103
ammp            4                2.64734
ammp            5                2.67462
ammp            6                2.68097
ammp            7                2.68631
ammp            8                 2.6904
ammp            9                2.69517
applu           0               0.678798
applu           10              0.922213
applu           1               0.901234
applu           11              0.923596
applu           12              0.923596
applu           2               0.901657
applu           3               0.903176
applu           4               0.908912
applu           5               0.913879
applu           6               0.914885
applu           7               0.915516
applu           8               0.917368
applu           9               0.920753
apsi            0                1.09037
apsi            10               2.20494
apsi            1                1.16651
apsi            11               2.24381
apsi            12               2.24381
apsi            2                1.49532
apsi            3                1.79137
apsi            4                1.79581
apsi            5                1.79601
apsi            6                1.80062
apsi            7                1.91269
apsi            8                 1.9579
apsi            9                2.00872
    ...

I want to sort it according to the first field and then the second. The problem is that I want lexicographical sort for the first field and numerical for the second.

I have tried the following:

cat tmp.txt | sort -k1,2

sorts both fields lexicographically

cat tmp.txt | sort -k1 | sort -n -k2

the second sort messes the first.

cat tmp.txt | sort -s -k1.2n

supposedly stable sort that does the second field numerically. Does not work, and sorts second field lexicographically...

Ideas??

like image 481
vkontori Avatar asked Dec 11 '12 08:12

vkontori


1 Answers

Try:

sort -k 1,1 -k 2,2n file

This will sort on the first field alphabetically and then on the second field numerically.

The sort man page has some examples.

like image 114
dogbane Avatar answered Sep 18 '22 12:09

dogbane