Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell sort array

Tags:

powershell

My array is spits out this.

a10
a11
a12
a6
a7
a8
a9

Any short/simple code to fix it to:

a6
a7
a8
a9
a10
a11
a12
like image 611
basickarl Avatar asked Dec 04 '22 04:12

basickarl


2 Answers

You can sort by expression, take everything after the first letter and cast it to integer:

$array | sort { [int]$_.substring(1)}

You can also make the solution more generic by removing any non-digit characters:

$array | sort { [int]($_ -replace '\D')}
like image 84
Shay Levy Avatar answered Dec 06 '22 18:12

Shay Levy


The easiest way in this case would be to zero-pad all numbers and use that for sorting:

$a | sort {
  [Regex]::Replace($_, '\d+', 
  {
    $args[0].Value.PadLeft(10, '0')
  })
}
like image 21
Joey Avatar answered Dec 06 '22 18:12

Joey