Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting numbers with multiple decimals in bash

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

like image 330
l'L'l Avatar asked Feb 13 '16 21:02

l'L'l


People also ask

How do you round to 3 decimal places in bash?

Equivalent C++ code can be(in main function): float a = 5+50*3.0/20.0 + (19*2.0)/7.0; cout<<setprecision(3)<<fixed<<a<<endl; bash.

How do I print a number with 2 decimal places in Linux?

%. 2f specifies that we're printing a decimal number - rounded to two decimal places. And the \n at the end specifies that we'll be printing a newline at the end of each line.

How do I sort by number in bash?

To sort by number pass the -n option to sort . This will sort from lowest number to highest number and write the result to standard output. Suppose a file exists with a list of items of clothing that has a number at the start of the line and needs to be sorted numerically.

Can bash handle decimals?

Default Bash Calculations It regrettably is unable to output decimals.


3 Answers

Try;

sort -g -k1 file

It will definitely work!!!

like image 140
Sushrat Mishra Avatar answered Oct 02 '22 16:10

Sushrat Mishra


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.

like image 23
karakfa Avatar answered Oct 02 '22 16:10

karakfa


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

like image 43
Fernando Cunha Avatar answered Oct 02 '22 16:10

Fernando Cunha