简体   繁体   English

BASH 按版本排序文件名

[英]BASH sorting file names by version

I need to order these file names (and I can't change them):我需要订购这些文件名(我无法更改它们):

  • file_31_stable.sql file_31_stable.sql
  • file_32_stable.sql file_32_stable.sql
  • file_310_stable.sql file_310_stable.sql
  • file_41_stable.sql file_41_stable.sql
  • file_42_stable.sql file_42_stable.sql
  • file_410_stable.sql file_410_stable.sql

This is also the expected order that I want to display them, because I have to get the last one.这也是我想要显示它们的预期顺序,因为我必须得到最后一个。

When I use the command当我使用命令时

find ./databases/ -iname file_*.sql | sort -V

The output is this:输出是这样的:

file_31_stable.sql
file_32_stable.sql
file_41_stable.sql
file_42_stable.sql
file_310_stable.sql
file_410_stable.sql

There is a form to order using the first number of the file and then the rest, or a command that will display the expected order?有一个表格可以使用文件的第一个数字然后其余的数字进行订购,或者有一个命令可以显示预期的顺序?

Without any separators, version 310 is obviously newer than version 41.没有任何分隔符,版本 310 显然比版本 41 新。

If you can devise a way to automatically add a separator, of course do that.如果您可以设计一种自动添加分隔符的方法,当然可以这样做。 Maybe也许

find ./databases/ -iname 'file_*.sql' |
sed 's/^\([^_]*_\)\([0-9]\)\([0-9]*\)/\2.\3\t\1\2\3/' |
sort -k1 -V |
cut -f2-

if you know the major version must always be a single digit;如果您知道主要版本必须始终是一位数; but obviously, in the general case, no such assumptions can be made.但显然,在一般情况下,不能做出这样的假设。

This adds a column before the actual value, sorts on that, and then peels off the added column;这会在实际值之前添加一列,对其进行排序,然后剥离添加的列; see also Schwartzian transform .另见施瓦兹变换 Before the cut , the output from sort looks likecut之前, sort的输出看起来像

3.1     file_31_stable.sql
3.2     file_32_stable.sql
3.10    file_310_stable.sql
4.1     file_41_stable.sql
4.2     file_42_stable.sql
4.10    file_410_stable.sql

If your sed does not recognize \\t as a tab, maybe try putting a literal tab (I can't do that here because Stack Overflow renders tabs as spaces).如果您的sed无法将\\t识别为制表符,则可以尝试放置一个文字制表符(我不能在这里这样做,因为 Stack Overflow 将制表符呈现为空格)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM