简体   繁体   English

UNIX:按编号/版本对文件进行排序,不使用0填充

[英]UNIX: Sort files by number/version without 0 padding

Ultimately, I wanted to set the latest version as an environment variable, so supplementing the selected answer (which provided me the correct sorting): 最终,我想将最新版本设置为环境变量,因此补充所选答案(这为我提供了正确的排序):

export LATEST_VERSION=$(printf '%s\n' * | sort -rV | head -1)

I have a directory with the following directory names: 我有一个目录,其中包含以下目录名称:

ls -1r .
2.0
1.8
16.1
16.0
15.5
15.0
14.5
14.1
14.0
1.3
1.2
1.1.5
1.1.3
1.1.2

I would like to sort them to get the latest release version: 我想对它们进行排序以获得最新版本:

ls -1r . | head -1
16.1

So the underlying order should look like this: 因此基础订单应如下所示:

16.1
16.0
15.5
15.0
14.5
14.1
14.0
2.0
1.8
1.3
1.2
1.1.5
1.1.3
1.1.2

Any help would be greatly appreciated. 任何帮助将不胜感激。 Simpler the better, but I'm open to any solution. 越简单越好,但我对任何解决方案都持开放态度。 Thanks! 谢谢!

Modern GNU sort offers a -V flag for sorting according to version number rules: 现代GNU排序提供-V标志,用于根据版本号规则进行排序:

$ printf '%s\n' * | sort -rV
16.1
16.0
15.5
15.0
14.5
14.1
14.0
2.0
1.8
1.3
1.2
1.1.5
1.1.3
1.1.2

Note that the above does not use ls . 注意,上面没有使用ls As a general rule, you shouldn't parse the output of ls(1) . 作为一般规则, 您不应解析ls(1)的输出

Documentation 文档

From man sort : man sort

-V, --version-sort -V, - version-sort
natural sort of (version) numbers within text 文本中的自然类型(版本)数字

The above is from the GNU man page. 以上内容来自GNU手册页。

FreeBSD's sort also supports -V . FreeBSD的排序也支持-V

OSX OSX

Apple's sort is a GNU sort from the year 2005 which predates support for the -V option. Apple的排序是从2005年开始的GNU排序,早于对-V选项的支持。 A work-around can be found here . 可以在这里找到解决方法。 (Hat tips: l'L'l, mklement0) (帽子提示:l'L'l,mklement0)

FWIW, I'm in Mac OS right now, and haven't booted over to linux to test. FWIW,我现在在Mac OS,并没有启动到linux进行测试。 But, it looks like sort with the numeric option has the smarts to do it: 但是,看起来像使用数字选项的排序有聪明才能做到:

But, I have a directory with your subdirectories in it, and ls sorts it badly: 但是,我有一个包含子目录的目录,并且ls严重排序:

/Users/thedave/tmp $ ls -1r
2.0
16.1.12
16.1
16.0
15.5
15.0
14.5
14.1
14.0
1.8
1.3
1.2
1.1.5
1.1.3
1.1.2
1.1
1.0.1
1.0

sort(1) accepts '-n' for numeric and '-r' for reverse: sort(1)接受'-n'表示数字,' - r'表示反向:

/Users/thedave/tmp $ ls | sort -rn
16.1.12
16.1
16.0
15.5
15.0
14.5
14.1
14.0
2.0
1.8
1.3
1.2
1.1.5
1.1.3
1.1.2
1.1
1.0.1
1.0

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

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