Sorting Numbers with Multiple Decimals in Bash

Sorting numbers with multiple decimals in bash

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

bash sorting numbers with decimals

With GNU sort:

sort -t "." -n -k1,1 -k2,2 file

Output:


1.1
1.2
1.10
3.2

Sorting decimals

You do not need to "${list[@]}" but just $list because it is just a string. Otherwise it gets all numbers in the same field.

$ for j in $list; do echo $j; done | sort -n
1
2
2.1
5

With your previous code it was not sorting at all:

$ list="77 1 2 5 2.1 99"
$ for j in "${list[@]}"; do echo "$j"; done | sort -n
77 1 2 5 2.1 99


Related Topics



Leave a reply



Submit