12

In bash using sort with the -n option doesn't give me the expected result.

$ cat numbers | sort -n
1.0
1.1
1.11.4
1.15
1.3
1.3.3
1.4-p1
1.6.1
2.2.10
2.2.2
2.4
2.4.6

I tried using -k1, -k1.1n, etc. (-k1.3n gets the order correct only for numbers starting with 1). It seems there's something very basic I'm missing here...

ivanleoncz
  • 9,070
  • 7
  • 57
  • 49
l'L'l
  • 44,951
  • 10
  • 95
  • 146

4 Answers4

23

There is a special flag for this -V for version numbers

$ sort -V numbers

1.0
1.1
1.3
1.3.3
1.4-p1
1.6.1
1.11.4
1.15
2.2.2
2.2.10
2.4
2.4.6

ps. this option is available in GNU Coreutils and may be missing in other implementations.

karakfa
  • 66,216
  • 7
  • 41
  • 56
  • 2
    This is not a valid option on OSX. – Joao Morais Feb 13 '16 at 22:40
  • 3
    As a point of minor interest: the `sort` that comes with OS X actually _is_ GNU `sort`, but it it is very old, and predates support for `-V`; as of OS X 10.11, the version number is `sort (GNU coreutils) 5.93`. – mklement0 Jul 08 '16 at 23:05
  • 2
    @mklement0: It appears they've added `-V` to macOS `sort --version 2.3-Apple (99)`. – l'L'l May 18 '18 at 05:46
11
sort -g numbers

It will do. As per sort man page, -g is meant for numerical sorting:

-g, --general-numeric-sort

compare according to general numerical value

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Fernando Cunha
  • 111
  • 1
  • 3
9

You need the -t. flag to specify '.' as your separator, and the multiple key position specifiers handles the progressively longer/deeper numbers. I still don't quite understand exactly how it works, but it works ...

 sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n numbers

or

 cat numbers | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n
Buddy Yaussy
  • 535
  • 2
  • 7
1

Try;

sort -g -k1 file

It will definitely work!!!