4

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

4 Answers 4

11

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')}
Sign up to request clarification or add additional context in comments.

2 Comments

Your second line "$array | sort { [int]($_ -replace '\D')}" was able to fix my array filled with "2012-03-02_log-X.txt". Thank you!
FYI: If you just have an array of string (and smart-numbering is an issue), all you need is $array | sort
5

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')
  })
}

2 Comments

@Joey $a | sort { $_ -replace '\d+' , $_.padleft(10,'0') } is good the same? or there is something wrong in this way?
There is. $_ 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.
3

These are hex values, right? ;-)

$array | sort {[convert]::toint32("$_",16)}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.