简体   繁体   English

Powershell,按文件名末尾的版本号对文件列表进行排序?

[英]Powershell, Sort a list of files by version number at the end of the filename?

How would you sort this filename list with PowerShell so they will appear in descending version order? 如何使用PowerShell对此文件名列表进行排序,以便它们以降序版本的形式出现?

I only need the highest version filename. 我只需要最高版本的文件名。

Name
----
CYFS_PreK_1_0_1_10
CYFS_PreK_1_0_1_11
CYFS_PreK_1_0_1_12
CYFS_PreK_1_0_1_13
CYFS_PreK_1_0_1_14
CYFS_PreK_1_0_1_15
CYFS_PreK_1_0_1_16
CYFS_PreK_1_0_1_17
CYFS_PreK_1_0_1_18
CYFS_PreK_1_0_1_19
CYFS_PreK_1_0_1_20
CYFS_PreK_1_0_1_21
CYFS_PreK_1_0_1_22
CYFS_PreK_1_0_1_23
CYFS_PreK_1_0_1_8
CYFS_PreK_1_0_1_9

The following will select "CYFS_PreK_1_0_1_9" since it is the highest number alphabetically as there are no leading zeros in the version numbers. 以下将选择“CYFS_PreK_1_0_1_9”,因为它是按字母顺序排列的最高数字,因为版本号中没有前导零。

$lastVersion = get-childitem $src |
    sort-object -descending | 
    select-object -First 1 -Property:Name

However, I am looking for "CYFS_PreK_1_0_1_23" 但是,我正在寻找“CYFS_PreK_1_0_1_23”

UPDATE: 更新:

If we only care about the final set of numbers, we can split the name for underscores and sort the final segment numerically. 如果我们只关心最后一组数字,我们可以拆分下划线的名称,并以数字方式对最终段进行排序。

Get-ChildItem $_ | 
    Sort-Object {[int] $_.Name.Split("_")[5]} -Descending |
    select-object -First 1 -Property:Name

This works for this set, however, if we rev to version 1_0_2_x, then it breaks again as the final 1 in 1_0_2_1 is less than 23 in 1_0_1_23. 这适用于此集合,但是,如果我们转换为版本1_0_2_x,则它会再次中断,因为1_0_2_1中的最后1在1_0_1_23中小于23。

You can use the [Version] type to do the version sorting. 您可以使用[Version]类型进行版本排序。 This only takes the version into account (so it doesn't care about the beginning of the filename): 这只考虑了版本(所以它不关心文件名的开头):

dir $_ |
    Sort-Object { 
        [Version] $(if ($_.BaseName -match "(\d+_){3}\d+") { 
                        $matches[0] -replace "_", "."
                    } 
                    else { 
                        "0.0.0.0"
                    })  
    } | select -last 1 -ExpandProperty Name

There may be a better way, but this works: 可能有更好的方法,但这有效:

Get-ChildItem $_ | 
    Sort-Object {[int]$_.Name.Split("_")[2], [int]$_.Name.Split("_")[3], [int]$_.Name.Split("_")[4], [int]$_.Name.Split("_")[5]} -Descending |
    select-object -First 1 -Property:Name
ls | sort -Descending { [version]($_ -replace 'CYFS_PreK_' -replace '_','.') } 


    Directory: /Users/js/foo

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
------           7/22/19  8:34 PM              3 CYFS_PreK_1_0_1_10
------           7/22/19  8:34 PM              3 CYFS_PreK_1_0_1_9
------           7/22/19  8:34 PM              3 CYFS_PreK_1_0_1_8

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

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