Search code examples
linuxunixsortingawkgnu-coreutils

Sorting numeric columns based on another numeric column


I have the following file:

BTA Pos KLD 

4   79.7011 5.7711028907

4    79.6231    5.7083918219

5   20.9112 4.5559494707

5    50.7354    4.2495580809

5   112.645 4.0936819092

6    72.8212    4.9384741047

6   18.3889 7.3631759258

I want to use AWK or bash commands to sort the second column based on the first column to have the output as follows:

4    79.6231    5.7083918219    

4   79.7011 5.7711028907

5   20.9112 4.5559494707

5    50.7354    4.2495580809

5   112.645 4.0936819092

6   18.3889 7.3631759258

6    72.8212    4.9384741047

Solution

  • sort numerically on column one then on column two:

    $ sort -nk1,1 -nk2,2 file
    BTA     POS      KLD
    4       79.6231  5.7083918219
    4       79.7011  5.7711028907
    5       20.9112  4.5559494707
    5       50.7354  4.2495580809
    5       112.645  4.0936819092
    6       18.3889  7.3631759258
    6       72.8212  4.9384741047