0

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
1
  • see man sort, and man uniq. Jan 20, 2019 at 16:11

1 Answer 1

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 .