Using powershell only, sort a text file with 300 lines, first by string length and then, once in that length, set them all alphbetically

Viewed 263

I am trying to do this as a one liner in powershell, so that I can move on to check these strings against a check string. The trouble I am having is that no matter what I do, I can only set it by string length.

The following attempts failed to get the required result.One does text great, the other by length successfully. I have also tried to pipe them in but I believe that neither accept pipeline input.

Your help is appreciated as am new to powershell.

PS C:\Users\IEUser> Get-Content Desktop/dict.txt | Sort-Object 
PS C:\Users\IEUser> Get-Content Desktop/dict.txt | Sort-Object -Property Length 
1 Answers

Given the sample array $toSort:

$toSort = @(
    'abcdefghwxyefg'
    'abcdefghghijkl'
    'abcdefghwxyefgabcdzx'
    'abcdefghwxyefgabcdef'
    'abcdzx'
    'abcdef'
    'abzxc'
    'abcde'
    'wxy'
    'efg'
    'abcdefgh'
    'ijklmnop'
)

You can use Sort-Object to sort the array first by the Length property and then by alphabetical order like this:

$toSort | Sort-Object Length, { $_ }

Thanks Mathias for pointing it out, I was previously using { $_[0] } which would sort only the first char of each line.


Including how the actual answer should be:

Get-Content Desktop/dict.txt | Sort-Object -Property Length, { $_ } |
    Out-File path/to/sortedDict.txt

If you want to have some fun with LINQ you can accomplish the same using first OrderBy to sort by Length and ThenBy alphabetical order:

[Linq.Enumerable]::ThenBy(
    [Linq.Enumerable]::OrderBy($toSort, [Func[object, int]]{param($s) $s.Length }),
    [Func[object, string]]{param($s) $s }
)
Related