14

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...

4 Answers 4

25

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This is not a valid option on OSX.
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: It appears they've added -V to macOS sort --version 2.3-Apple (99).
12
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

Comments

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

Comments

1

Try;

sort -g -k1 file

It will definitely work!!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.