Sort a list of strings in Bash numerically according to specific substring

Viewed 75

I have a list of strings which unfortunately doesn't seem to lend itself to be sorted with sort --key=???.

This is the string:

Original                        40.101 s                   40.556 s
User XYZ                         3.389 s                    3.261 s
User XYZ/User ABC                5.342 s                    5.300 s
Somebody else                   32.531 s                   32.154 s
My friend Tony the Pony          5.905 s                    5.639 s
L33t                            27.007 s                   26.893 s
Serial port                      7.871 s                    7.738 s
Unknown user                     2.815 s                    2.700 s

I'd like it to be sorted according to the first number, ascending or descending doesn't really matter although it would be great to know a solution that can in principle do both.

I tried sort --key=2 <<HERE ... HERE but unsurprisingly this just leads to a random order.

1 Answers

Assuming your input file is correctly indented with space, use -k option of sort command:

sort -n -k1.30 file

or the reverse way:

sort -nr -k1.30 file

1.30 means skip the 30 first characters of field number one.

The -n switch sorts numerically instead of lexicographically.

Related