I have a .txt file something like this:
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
I have the following code for sorting:
$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
So this would have to display this:
First-a, Second-a, Third-a, Fourth-a
Since 98 is the highest number
CodePudding user response:
Since you're only looking for string output, there's no need to construct intermediate [pscustomobject]
representations:
Use a script block as a sort criterion for
Sort-Object
that can act directly on the input lines.Use
-replace
, the regular-expression-based string replacement operator to remove the last field from the output line of interest.
Get-Content file.txt |
Sort-Object { [int] ($_ -split ', ')[-1] } -Descending |
Select-Object -First 1 |
ForEach-Object { $_ -replace ', [^,] $' }
CodePudding user response:
It would seem to be easier to treat this as a CSV file and let the PowerShell CSV functions do more of the work. Field names can be specified on the Import-Csv
command.
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)"
}