在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:50:04  来源:igfitidea点击:

Sorting strings with numbers in Bash

bashsortingalphanumeric

提问by hardcode57

I've often wanted to sort strings with numbers in them so that, when sorting e.g. abc_2, abc_1, abc_10the 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 sortwith a --sensible_numericaloption?

有没有胡子的 *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