Linux 如何从 Bash 对包含公共前缀和后缀的字符串进行数字排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13088370/
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-08-06 17:37:53  来源:igfitidea点击:

How to sort strings that contain a common prefix and suffix numerically from Bash?

linuxbashunixsorting

提问by AWE

Here is a list of files:

以下是文件列表:

some.string_100_with_numbers.in-it.txt
some.string_101_with_numbers.in-it.txt
some.string_102_with_numbers.in-it.txt
some.string_23_with_numbers.in-it.txt
some.string_24_with_numbers.in-it.txt
some.string_25_with_numbers.in-it.txt

Now I would like to sort it numerically. Starting with *23* and ending with *102*.

现在我想按数字对它进行排序。以 *23* 开头,以 *102* 结尾。

I have tried -nand -g. -tdoes not help in these messy strings.

我试过-n-g-t对这些凌乱的字符串没有帮助。

Can I ignore leading strings to the number with an option or do I have to be clever and script?

我可以使用选项忽略数字的前导字符串还是我必须聪明和脚本?

采纳答案by Steve

Use ls -lv

ls -lv

From the man page:

从手册页:

-v     natural sort of (version) numbers within text

回答by Jo?o Silva

Try the following:

请尝试以下操作:

sort -t '_' -k 2n
  • -t '_'(sets the delimiter to the underscore character)
  • -k 2n(sorts by the second column using numeric ordering)
  • -t '_'(将分隔符设置为下划线字符)
  • -k 2n(使用数字顺序按第二列排序)

DEMO.

演示

回答by tripleee

In the general case, try the Schwartzian transform.

在一般情况下,请尝试施瓦兹变换

Briefly, break out the number into its own field, sort on that, and discard the added field.

简而言之,将数字分解到其自己的字段中,对其进行排序,然后丢弃添加的字段。

# In many shells, use ctrl-v tab to insert a literal tab after the first 
sed 's/^\([^0-9]*\)\([0-9][0-9]*\)/   /' file |
sort -n |
cut -f2-

This works nicely if the input doesn't have an obvious separator, like for the following input.

如果输入没有明显的分隔符,这会很好地工作,例如以下输入。

abc1
abc10
abc2

where you would like the sort to move the last line up right after the first.

您希望排序在第一行之后将最后一行向上移动。

回答by Rhubbarb

If available, simply use sort -V. This is a sort for version numbers, but works well as a "natural sort" option.

如果可用,只需使用sort -V. 这是对版本号的排序,但作为“自然排序”选项效果很好。

$ ff=$( echo some.string_{100,101,102,23,24,25}_with_numbers.in-it.txt )

Without sort:

无排序:

$ for f in $ff ; do echo $f ; done
some.string_100_with_numbers.in-it.txt
some.string_101_with_numbers.in-it.txt
some.string_102_with_numbers.in-it.txt
some.string_23_with_numbers.in-it.txt
some.string_24_with_numbers.in-it.txt
some.string_25_with_numbers.in-it.txt

With sort -V:

使用排序 -V:

$ for f in $ff ; do echo $f ; done | sort -V
some.string_23_with_numbers.in-it.txt
some.string_24_with_numbers.in-it.txt
some.string_25_with_numbers.in-it.txt
some.string_100_with_numbers.in-it.txt
some.string_101_with_numbers.in-it.txt
some.string_102_with_numbers.in-it.txt