user3437245
user3437245

Reputation: 347

count occurrence of column in another column with awk

How would you count occurrence of column 2 in column 1 with awk?

Input:

AA BB 
BB AA
BB CC
AA BB
CC AA
CC BB
CC CC
BB BB

Output:

AA BB 3
BB AA 2
BB CC 3
AA BB 3
CC AA 2
CC BB 3
CC CC 3
BB BB 3

Upvotes: 0

Views: 147

Answers (1)

Kent
Kent

Reputation: 195039

with your example input, this gives the same output as you expected

kent$  awk 'NR==FNR{a[$1]++;next}{print $0,a[$2]}' file file
AA BB 3
BB AA 2
BB CC 3
AA BB 3
CC AA 2
CC BB 3
CC CC 3
BB BB 3

Upvotes: 1

Related Questions