PowerShell One-Liner: sort | uniq -c

Another track, this time for me to collect useful scripting snippets.  Here’s one:

 In Unix, if I have a non-unique list of strings, it’s sometimes interesting to see the frequency in which the particular strings appear.  For example, I have a list of errors from a long, and need the top 10.  In Unix, it’s pretty simple:

bash$ cat file | sort | uniq -c | sort -nr | head -10

Okay, maybe ‘simple’ may be a little overstating things. Let’s cut to the chase.  Here’s how we do it in PowerShell:

 PSH> Get-Content file | Group-Object | Format-Table count, name | Select-Object -First10

That’s expanding all the commands.

PSH> gc file | group | ft count, name | select -f 10

That’s shortest form, but whoever has to maintain that script will hunt us down and for good reason. 


Comments (1)

  1. Jarrod says:

    bash$ cat file | sort | uniq -c | sort -nr | head -10

    could be simplified to

    bash$ sort file | uniq -c | sort -nr | head -10