Use sort to sort numerical column

How to sort the following output based on lowest to highest BE?
The following sort does not work.

$ sort -t. -k1,1n -k2,2n bfd.txt

 BE31.116       0s               0s               DOWN DAMP
 BE31.116       0s               0s               DOWN DAMP
BE31.117       0s               0s               DOWN DAMP
 BE31.702       0s               0s               DOWN DAMP
 BE31.961       0s               0s               DOWN DAMP
 BE62.2040      0s               0s               DOWN DAMP  <---- should be last
 BE31.3918      0s               0s               DOWN DAMP

Thanks.

Hi, try so

sort -k1.3,1 bfd.txt

--- Post updated at 18:34 ---

sort -V bfd.txt

--- Post updated at 18:42 ---

sort -t. -k1.3,1.4n -k2,2n bfd.txt

Try:

sed 's/^ *//' file | sort -k1.3,1n
1 Like

Thanks Scrutinizer
@sand1234, If there are leading spaces the following command gives the order as you showed above.

sort -bV bfd.txt
1 Like

Thanks nezabudka,

Indeed -b can be used to ignore leading blanks; the sed statement can be used to remove leading spaces and correct the output..

The -V option is a non-standard extension that is carried by GNU Sort and BSD Sort and is used when the dot in the number signifies a major.minor version number. The -n option is used for numerical sorts.

They give different results, depending on the meaning of the dotted number, the OP has not indicated what is the case..

S.

1 Like

reviewing solutions

--- Post updated at 12:38 PM ---

Hi,

1st solution works:

$ sed 's/^ *//' bfd.txt | sort -bV

BE31.116              0s               0s               DOWN DAMP
BE31.116               0s               0s               DOWN DAMP
BE31.117              0s               0s               DOWN DAMP
BE31.702                 0s               0s               DOWN DAMP
BE31.961              0s               0s               DOWN DAMP
BE31.3918           0s               0s               DOWN DAMP
BE62.2040               0s               0s               DOWN DAMP

2nd solution fails:

$ sed 's/^ *//' bfd.txt | sort -k1.3,1n

BE31.116              0s               0s               DOWN DAMP
BE31.116              0s               0s               DOWN DAMP
BE31.117               0s               0s               DOWN DAMP
BE31.3918             0s               0s               DOWN DAMP  <----- incorrect
BE31.702                 0s               0s               DOWN DAMP
BE31.961            0s               0s               DOWN DAMP
BE62.2040               0s               0s               DOWN DAMP

Can you please shed some light on why the 2nd solution does not work?
Also, why do we need 1n after -k1,3? I get the same result with and without this switch.

Thanks,

See post #5. It is the difference between numerical and version number sort..

With version numbers 1.11 comes after 1.9. With numerical sort 1..11 is smaller than than 1.9 .

You had not specified which case applies..

1 Like