PowerShell equivalent to sort|uniq -c|sort -nr

This topic contains 4 replies, has 3 voices, and was last updated by Profile photo of Horst Meier Horst Meier 1 month, 2 weeks ago.

  • Author
    Posts
  • #55394
    Profile photo of Horst Meier
    Horst Meier
    Participant

    Hello guys,

    I'm looking for a PowerShell one liner doing the same as "sort | uniq -c | sort -nr" on a Unix shell.

    Using for example

    @(55,22,33,44,11,44,33,22,11,33,22,11,22,11,11) | group-object | format-table -h count,name

    will deliver

    1 55
    4 22
    3 33
    2 44
    5 11

    But the goal is to have this list sorted by frequency in descending order.

    Trying

    @(55,22,33,44,11,44,33,22,11,33,22,11,22,11,11) | group-object | format-table -h count,name | sort-object -descending

    doesn't work.

    Using a temporary file will do the job but this is not an elegant solution.

    @(55,22,33,44,11,44,33,22,11,33,22,11,22,11,11) | group-object | format-table -h count,name >tmp
    get-content tmp | sort-object -descending

    5 11
    4 22
    3 33
    2 44
    1 55

    Anybody to propose a clean and straightforward way to execute such task in PowerShell just like in the Unix shell?

  • #55396
    Profile photo of Christian Sandfeld
    Christian Sandfeld
    Participant

    Hi Horst

    The problem is with your use of the Format-Table commandlet. PowerShell send objects through the pipeline, and all cmdlets are made to work with objects rather than text. But as soon as you use one of the 'Format-' cmdlets, you no longer have true objects, and the other cmdlets can't work with that output.

    Your problem could be solved with this one-liner:

    @(55,22,33,44,11,44,33,22,11,33,22,11,22,11,11) | Group-Object | Select-Object -Property Count, Name | Sort-Object -Property Count -Descending
    

    Or if you want it shorter, you can do it with aliases instead:

    @(55,22,33,44,11,44,33,22,11,33,22,11,22,11,11) | group | select Count, Name | sort Count -d
    

    /Christian

  • #55403
    Profile photo of Horst Meier
    Horst Meier
    Participant

    Hello Christian,

    very cool.
    This is it.

    Thanks,
    Horst

  • #55414
    Profile photo of Dan Potter
    Dan Potter
    Participant

    Some of us frequent both sapien and powershell.org forums. Be patient for an answer=D

    • #55709
      Profile photo of Horst Meier
      Horst Meier
      Participant

      Some of us frequent both sapien and powershell.org forums. Be patient for an answer=D

      Sorry 'bout that, chief.
      Had some trouble to register here...

You must be logged in to reply to this topic.