How to sort data by age with powershell

Viewed 55

trying to sort a txt file in powershell by age when the data looks like this:

Smith,John,65
Walker,Luke,25
Mano,Jill, 88

trying to get it to look like this

Mano,Jill,88
Smith,John,65
Walker,Luke,25

Ive tries Format-Table but would just sort the names in order

any suggestions would be great

1 Answers

Use Sort-Object with a calculated property:

# Simulate input from a file (e.g., Get-Content in.txt)
$fileLines = 
@'
Smith,John,65
Walker,Luke,25
Mano,Jill,88
'@ -split '\r?\n'

$fileLines | Sort-Object -Descending { [int] ($_ -split ',')[-1] } 

This sorts by age only. You could add additional sort criteria in order to sort by name among those with the same age.

At that point, however, you're better off working with your data as CSV data, using Import-Csv in order to parse the file into objects you can work with (the example uses the in-memory cmdlet version, ConvertFrom-Csv):

# Simulate input from a file (e.g., Import-Csv in.csv)
$csvRows = @'
Smith,John,65
Walker,Luke,25
Mano,Jill,88
'@ | ConvertFrom-Csv -Header last, first, age

# Sort by age, then by name.
$csvRows | 
  Sort-Object -Descending { [int] $_.age }, last, first

Note:

  • Since your data lacks a header (column names), it was supplied via a -Header argument.

  • Import-Csv / ConvertTo-Csv parse CSV data into [pscustomobject] instances whose properties are named for the CSV columns and contain the field values.

  • You can use Export-Csv to export the results back to a CSV file, invariably with a header.

    • In Windows PowerShell, you'll invariably get double-quoted field values.
    • In PowerShell (Core) 7+, you can control the quoting behavior with the -UseQuotes and QuoteField parameters.
    • Use -Encoding as needed to control the output file's character encoding; notably, in Windows PowerShell ASCII(!) files are produce by default; in PowerShell (Core) 7+, BOM-less UTF-8 is the sensible default (which, unlike in Windows PowerShell, is the default across all cmdlets).
Related