Counting with sort and uniq

Written by Benjamin Cane on 2011-08-06 02:20:00

Here is another quick example of how to get a count of how many times a string appears. For my example I am going to use this output.

$ cat /etc/passwd | cut -d: -f7
/bin/bash
/bin/sh
/bin/sh
/bin/sh
/bin/sync
/bin/sh
/bin/sh
/bin/sh

These are the shells of users on my system, what if I wanted to see what the most common shell was?

$ cat /etc/passwd | cut -d: -f7 | sort | uniq -c | sort -nk1
1 /bin/sync
2 /usr/sbin/nologin
4 /bin/false
5 /bin/bash
20 /bin/sh

In order to get this result I take my output and send it to sort, this command will sort the output alphabetically. From there we pipe it to uniq -c which will find all of the unique occurrences of a string and print the number of times it shows up. We then sort by that number and BAM, we have a list of shells and how many users are using them.


Picture of Benjamin Cane

Benjamin is a Systems Architect working in the financial services industry focused on platforms that require Continuous Availability. He has been working with Linux and Unix for over 10 years now and has recently published his first book; Red Hat Enterprise Linux Troubleshooting Guide.

Publications

Identify, capture and resolve common issues faced by Red Hat Enterprise Linux administrators using best practices and advanced troubleshooting techniques

What people are saying:
Excellent, excellent resource for practical guidance on how to troubleshoot a wide variety of problems on Red Hat Linux. I particularly enjoyed how the author made sure to provide solid background and practical examples. I have a lot of experience on Red Hat but still came away with some great practical tools to add to my toolkit. - Amazon Review

Sponsored by