在 powershell 中对具有起始编号的字符串列表进行排序

Sort list of strings with starting number in powershell

我是 Powershell 的新手,非常感谢您的帮助。

我有一个字符串列表(文件名),它们以数字开头,例如。 "1.第一档", "2.第二档" ... "21.第二十一档".

我想按照起始编号的顺序排序。但是当我执行“$List | sort {$_.Name} -Unique”时,它将以“1.”开头,然后下一项是“11”。而不是“2.”

请帮忙。

这是一种方法:

$test = @('1. First', '2. Second', '11. Eleventh')
$sort = @()
foreach($item in $test){
  $item -match '^(\d+).*'
  $temp = New-Object PSCustomObject -property @{'Number' = [int]$matches[1]}
  $sort += $temp
}
$sort | Sort-Object Number | Select-Object Data

为了稍微简化之前的答案,您可以这样做:

$test | Sort-Object -Property @{ Expression={[int]$_.substring(0,$_.IndexOf('.'))}; Ascending=$true }

还有一个选项:

$col = @(
'1. first file'
'2. second file'
'11. eleventh file'
'21. twenty-first file'
)

$ht = @{}
$col | foreach {$ht[$_ -replace '\D+$'] = $_}
[int[]]$ht.keys | sort | foreach {$ht["$_"] }

1. first file
2. second file
11. eleventh file
21. twenty-first file