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...
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.
%. 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.
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.
Default Bash Calculations It regrettably is unable to output decimals.
Try;
sort -g -k1 file
It will definitely work!!!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With