bash 在bash中对具有多个小数的数字进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35385802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting numbers with multiple decimals in bash
提问by l'L'l
In bash
using sort
with the -n
option doesn't give me the expected result.
在bash
使用sort
与-n
选择不给我预期的结果。
$ 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...
我尝试使用-k1
,-k1.1n
等(-k1.3n
仅对以 开头的数字获取正确的顺序1
)。似乎我在这里遗漏了一些非常基本的东西......
采纳答案by Buddy Yaussy
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 ...
你需要 -t。用于指定“.”的标志 作为分隔符,多个关键位置说明符处理逐渐变长/变深的数字。我仍然不太明白它是如何工作的,但它确实有效......
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
回答by karakfa
There is a special flag for this -V
for version numbers
-V
对于版本号,有一个特殊的标志
$ 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.
附:此选项在 GNU Coreutils 中可用,但在其他实现中可能会丢失。
回答by Fernando Cunha
sort -g numbers
It will do. As per sort man page, -g
is meant for numerical sorting:
它会做。根据排序手册页,-g
用于数字排序:
-g, --general-numeric-sort
compare according to general numerical value
-g, --general-numeric-sort
按一般数值比较