在 Bash 中用数字对字符串进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17061948/
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 strings with numbers in Bash
提问by hardcode57
I've often wanted to sort strings with numbers in them so that, when sorting e.g. abc_2, abc_1, abc_10
the result is abc_1, abc_2, abc_10
. Every sort mechanism I've seen sorts as abc_1, abc_10, abc_2
, that is character by character from the left.
我经常想对包含数字的字符串进行排序,以便在排序时,例如 abc_2, abc_1, abc_10
结果是abc_1, abc_2, abc_10
. 我见过的每一种排序机制abc_1, abc_10, abc_2
都是从左边开始一个字符一个字符地排序。
Is there any efficient way to sort to get the result I want? The idea of looking at every character, determining if it's a numeral, building a substring out of subsequent numerals and sorting on that as a number is too appalling to contemplate in bash
.
有什么有效的方法可以排序以获得我想要的结果?查看每个字符,确定它是否是数字,从后续数字中构建子字符串并将其作为数字进行排序的想法太可怕了,无法在bash
.
Has no bearded *nix guru implemented an alternative version of sort
with a --sensible_numerical
option?
有没有胡子的 *nix 大师实现了sort
一个--sensible_numerical
选项的替代版本?
回答by Grzegorz ?ur
Execute this
执行这个
sort -t _ -k 2 -g data.file
- -t separator
- -k key/column
- -g general numeric sort
- -t 分隔符
- -k 键/列
- -g 一般数字排序
回答by glenn Hymanman
I think this is a GNU extension to sort
, but you're looking for the --version-sort
(or -V
) option:
我认为这是 GNU 的扩展sort
,但您正在寻找--version-sort
(或-V
)选项:
$ printf "prefix%d\n" $(seq 10 -3 1)
prefix10
prefix7
prefix4
prefix1
$ printf "prefix%d\n" $(seq 10 -3 1) | sort
prefix1
prefix10
prefix4
prefix7
$ printf "prefix%d\n" $(seq 10 -3 1) | sort --version-sort
prefix1
prefix4
prefix7
prefix10
https://www.gnu.org/software/coreutils/manual/html_node/sort-invocation.html
https://www.gnu.org/software/coreutils/manual/html_node/sort-invocation.html
回答by Bill
Try this
尝试这个
$ cat a.txt
abc_1
abc_4
abc_2
abc_10
abc_5
$ sort -V a.txt
abc_1
abc_2
abc_4
abc_5
abc_10