Alexandros P
Alexandros P

Reputation: 21

How to count duplicates in Bash Shell

Hello guys I want to count how many duplicates there are in a column of a file and put the number next to them. I use awk and sort like this

awk -F '|' '{print $2}' FILE | sort | uniq -c

but the count (from the uniq -c) appears at the left side of the duplicates.

Is there any way to put the count on the right side instead of the left, using my code?

Thanks for your time!

Upvotes: 1

Views: 1892

Answers (5)

Starwalker
Starwalker

Reputation: 96

Check this command:

awk -F '|' '{c[$2]++} END{for (i in c) print i, c[i]}' FILE | sort

Use awk to do the counting is enough. If you do not want to sort by browser, remove the pipe and sort.

Upvotes: 0

CWLiu
CWLiu

Reputation: 4043

You can use awk to calculate the amount of duplicates, so your command can be simplified as followed,

awk -F '|' '{a[$2]++}END{for(i in a) print i,a[i]}' FILE | sort

Upvotes: 0

tso
tso

Reputation: 4924

awk -F '|' '{print $2}' FILE | sort | uniq -c| awk '{a=$1; $1=""; gsub(/^ /,"",$0);print $0,a}'

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133538

Though I believe you shouls show us your Input_file so that we could create a single command or so for this requirement, since you have't shown Input_file so trying to solve it with your command itself.

awk -F '|' '{print $2}' FILE | sort | uniq -c | awk '{for(i=2;i<=NF;i++){printf("%s ",$i)};printf("%s%s",$1,RS)}'

Upvotes: 3

Lohit Gupta
Lohit Gupta

Reputation: 1081

You can just use awk to reverse the output like below:

awk -F '|' '{print $2}' FILE | sort | uniq -c | awk {'print $2" "$1'}

Upvotes: 0

Related Questions