[英]Sorting of files based on version number in the middle of the file name
I am new to the power shell. 我是电源外壳的新手。 I am trying to sort a list of files which are having version number in the middle of the name.
我正在尝试对名称中间有版本号的文件列表进行排序。
Here is the list of files : 这是文件列表:
sample-file-1.1.0-patch.zip
sample-file-1.1.1-patch.zip
sample-file-1.1.2-patch.zip
sample-file-1.1.2.1-fix-patch.zip
sample-file-1.1.3-patch.zip
sample-file-1.1.3.1-fix-patch.zip
..
sample-file-1.1.15-patch.zip
sample-file-1.1.15.1-fix-patch.zip
sample-file-1.1.15.2-fix-patch.zip
..
sample-file-2.0.0-patch.zip
sample-file-2.0.1-patch.zip
..
I would request you to help me with the sorting logic. 我会请你帮我分类逻辑。
Thanks 谢谢
The simplest approach with your sample input is the following, which assumes that the first digit following -
starts the version number and that it ends with the last digit before a subsequent -
: 您的样本输入最简单的方法如下,它假定后面的第一个数字
-
开始版本号,并以后续的最后一个数字结束-
:
Get-ChildItem *.zip | Sort-Object { [version]($_.Name -replace '^[^\d]+-(.*\d)-.*', '$1') }
$_.Name -replace '^[^\\d]+-(.*\\d)-.*', '$1'
extracts the version number from each file name as a string. $_.Name -replace '^[^\\d]+-(.*\\d)-.*', '$1'
从每个文件名中提取版本号作为字符串。
[version]
casts that string to a version-number object ( System.Version
) [1] , which is sortable based on the version-number components. [version]
将该字符串强制转换为版本号对象( System.Version
) [1] ,该对象可根据版本号组件进行排序。
Passing the whole expression as a script block { ... }
to Sort-Object
means that sorting is based on the [version]
instances returned by the script block, evaluated for each input filename. 将整个表达式作为脚本块
{ ... }
传递给Sort-Object
意味着排序基于脚本块返回的[version]
实例,针对每个输入文件名进行评估。
[1] PSv5.1 introduced a related type, [System.Management.Automation.SemanticVersion]
, based on semantic versioning , which wouldn't work here, however, because it only supports 3 version-number components. [1] PSv5.1引入了一种基于语义版本控制的相关类型
[System.Management.Automation.SemanticVersion]
,但这不适用于此,因为它只支持3个版本号组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.