使用awk计算出现的条件

时间:2015-12-06 08:27:47

标签: regex awk

说数据集

Jack apple
Jack pear
Annie apple
Olivia grapes
Olivia pear
Olivia apple
Jack pear
Jack apple

每个水果我需要多少次购买它。例如,最终输出应为

apple, Annie, 1
apple, Jack, 2
apple, Olivia, 1
grapes, Olivia, 1
pear, Jack, 2
pear, Olivia, 1 

我不知道有多少种不同类型的水果或多少人。我能够得到特定水果的结果,但需要帮助包括所有类型的水果

awk '{
all[$1]++
if ($2=="apple") appcount[$1]++} END {for (user in all) print user,  appcount[user]}                                         

'

3 个答案:

答案 0 :(得分:3)

使用awk你可以这样做:

awk -v OFS=', ' '{seen[$2 OFS $1]++} END{for (i in seen) print i, seen[i]}' file
apple, Olivia, 1
grapes, Olivia, 1
pear, Olivia, 1
apple, Jack, 2
apple, Annie, 1
pear, Jack, 2

获得排序结果

awk -v OFS=', ' '{seen[$2 OFS $1]++} END{for (i in seen) print i, seen[i]}' file |
> sort -t, -k1
apple, Annie, 1
apple, Jack, 2
apple, Olivia, 1
grapes, Olivia, 1
pear, Jack, 2
pear, Olivia, 1

答案 1 :(得分:2)

使用排序辅助awk

$ sort -k2 -k1,1 names | uniq -c | awk -v OFS=", " '{print $3,$2,$1}'
apple, Annie, 1
apple, Jack, 2
apple, Olivia, 1
grapes, Olivia, 1
pear, Jack, 2
pear, Olivia, 1

答案 2 :(得分:1)

一体化perl替补:

perl -lane '$h{$F[1],", ",$F[0]}++ }{ print join ", ", $_, $h{$_} for sort keys %h' file
apple, Annie, 1
apple, Jack, 2
apple, Olivia, 1
grapes, Olivia, 1
pear, Jack, 2
pear, Olivia, 1