我有一個類似這樣的 .txt 檔案:
First, Second, Third, Fourth, -32
First-a, Second-a, Third-a, Fourth-a, 98
First-b, Second-b, Third-b, Fourth-b, 32
First-c, Second-c, Third-c, Fourth-c, 1
First-d, Second-d, Third-d, Fourth-d, -20
我有以下排序代碼:
$Line = $_.Trim() -Split ','
New-Object -TypeName PSCustomObject -Property @{
fst = $Line[0]
snd = $Line[1]
thrd = $Line[2]
frth = $Line[3]
fifth = [int]$Line[4]
}
} | Sort-Object -Descending fifth | Write-Host
所以這必須顯示:
First-a, Second-a, Third-a, Fourth-a
因為 98 是最高的數字
uj5u.com熱心網友回復:
由于您只是在尋找字串輸出,因此無需構建中間[pscustomobject]表示:
使用腳本塊作為排序標準,因為
Sort-Object它可以直接作用于輸入行。使用
-replace時,基于正則運算式的字串替換操作,以從感興趣的輸出線去掉最后一個欄位。
Get-Content file.txt |
Sort-Object { [int] ($_ -split ', ')[-1] } -Descending |
Select-Object -First 1 |
ForEach-Object { $_ -replace ', [^,] $' }
uj5u.com熱心網友回復:
將其視為 CSV 檔案并讓 PowerShell CSV 函式完成更多作業似乎更容易。可以在Import-Csv命令中指定欄位名稱。
Import-Csv -Path .\sortcsv.txt -Header @('first','second','third','fourth','fifth') |
Sort-Object {[int32]$_.fifth} |
Select-Object -Last 1 |
ForEach-Object {
Write-Host "$($_.first), $($_.second), $($_.third), $($_.fourth)"
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/374226.html
標籤:电源外壳
上一篇:組物件,獲取計數
