0

This question already has an answer here:

I have in file /tmp/users list of users ( each list contain diff users )

Example

more /tmp/users


root
kafka
yarn
hdfs
root
root
yarn
moon
apache
start
moon
apache

I want to print the users that appears in the file /tmp/users and count them as the following

Expected results

apache - 2
Hdfs - 1
Kafka - 1
Moon - 2
Root - 3
Start - 1
Yarn - 2

marked as duplicate by don_crissti, Romeo Ninov, Jeff Schaller, Thomas, roaima Jan 20 at 19:10

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2

You can get this with this pipeline, which though may not be the most homogeneous approach:

sort /tmp/users | uniq -c | awk '{print $2 " - " $1;}'

sort sorts the input, so that uniq can then process the entries. They need to be sorted. Finally awk produces the final report, which is a cosmetic operation. (Compare the output without it.)

Also, if the input contains empty lines, you may want to skip them. perl comes in handy:

perl -lne 'print unless /^\s*$/' in | sort | uniq -c | awk '{print $2 " - " $1;}'

Here's also a homogeneous Perl one liner:

perl -lne '($s)=/(\S+)/; $a{$s}++ if $s; END {print "$_ - $a{$_}" for (sort keys %a)}' /tmp/users

Not the answer you're looking for? Browse other questions tagged or ask your own question.