简体   繁体   中英

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?

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.

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

However, I am looking for "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.

You can use the [Version] type to do the version sorting. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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