'Sort text numerically in powershell

I have some data in a text string that I need to sort. Here's a snippet:

0 X6300H_INJ.xtf CSFFILE0032
1 X6301H_INJ.xtf CSFFILE0033
10 X6309H_INJ.xtf CSFFILE0041
11 X6310H_INJ.xtf CSFFILE0042
2 X6311H_INJ.xtf CSFFILE0043

I need to sort this data numerically by the first column. How can I do this?



Solution 1:[1]

To build on TheMadTechnician's helpful comment:

  • Pass a script block ({... }) to the Sort-Object cmdlet's (positionally implied)
    -Property parameter, which allows you to determine the sort criterion dynamically for each input line (object), accessible via the automatic $_ variable.

  • Inside the script block you can split each line into fields by whitespace using the unary form of the -split operator, extract the first field, and cast it as an integer ([int]), which then serves as the sort value.

    • As an aside: If all input strings represented numbers as a whole, the solution would be as simple as:

      '1', '10', '9' | Sort-Object { [int] $_ } # -> '1', '9', '10'
      
    • Analogously, if the number (strings) to sort by were stored in a property of the input objects (note that just Sort-Object Prop would sort lexically):

      @{ Prop='1' }, @{ Prop='10' }, @{ Prop= '9' } |
        Sort-Object { [int] $_.Prop }
      
@'
0 X6300H_INJ.xtf CSFFILE0032
1 X6301H_INJ.xtf CSFFILE0033
10 X6309H_INJ.xtf CSFFILE0041
11 X6310H_INJ.xtf CSFFILE0042
2 X6311H_INJ.xtf CSFFILE0043
'@ -split '\r?\n' |
  Sort-Object { [int] (-split $_)[0] }

Note: @'<newline>...<newline>'@ is a (verbatim) PowerShell here-string; -split '\r?\n' splits a multi-line string into an array of lines.

Output (correctly sorted by 1st column, numerically):

0 X6300H_INJ.xtf CSFFILE0032
1 X6301H_INJ.xtf CSFFILE0033
2 X6311H_INJ.xtf CSFFILE0043
10 X6309H_INJ.xtf CSFFILE0041
11 X6310H_INJ.xtf CSFFILE0042

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1