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
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')}
$array | sortThe 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')
})
}
$_ refers to the complete item, not the match in your case. Therefore the result isn't a0000000001 but a00000000a1. It probably ceases to work with multiple numbers in a string, although I'm too tired now to try. The solution above should yield a »natural« sort with almost any list of strings that contain numbers.You can simply use the sort method.
$myArray = $myArray | Sort-Object;
Some other answers may be more efficient regarding the particular array shown in the question, but in general this will do.
Credit: Add, Modify, Verify, and Sort Your PowerShell Array - Dr. Scripto