1

I can't figure out how to sort a string array first by letter then by number combination. Here is the sample:

$a = @('aa101','aa11','ab10','ab9','a111','a22','a01')

I would like to see the result after the sorting as follow:

a01
a22
a111
aa11
aa101
ab9
ab10

Please help me to find out the answer by using PowerShell script.

4
  • 1
    The sorting algorithm you describe (sort by first letter, then number), would yield a different result than your example Commented Dec 31, 2016 at 12:06
  • Hi, Mathias, what would be the result, could please explain? Commented Dec 31, 2016 at 12:09
  • Sorting these values by first letter has no effect on the set you've described (they all start with a), sorting by numbers you would get a01 first (01 is 1, the smallest number in the set), then ab9 (9 is the second-smallest), then ab10 etc. Commented Dec 31, 2016 at 12:11
  • Ahh, "first by letter", not "by first letter", my mistake Commented Dec 31, 2016 at 12:12

1 Answer 1

4

The Sort-Object cmdlet can take one or more scriptblocks as its Property argument. First argument should remove all the digits at the end, then remove all non-digits and cast to an integer:

$a |Sort-Object {"$_" -replace '\d',''},{("$_" -replace '\D','') -as [int]}
  • \d is regex for digits
  • \D is regex for anything that isn't digits
Sign up to request clarification or add additional context in comments.

3 Comments

YES! Thank you so much, Mathias! I didn't realize the sort-object can take two expressions separated by comma. I refined just a little bit to save some typing. $a | Sort-Object {"$_" -replace '\d'},{[int]("$_" -replace '\D')}
@LiangCui You can also combine expressions and property names if need be: $a |Sort-Object Length,{[int]("$_"-replace'\D','')}
uh... got it. I am so new to stackoverflow. My bad for the inconvenience.

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.