我想计算单个列中的事件数,并计算这些事件的输出计数以及计算的最后一次事件的完整记录。
这适用于计数,但也希望从输出中获得更多描述。
awk '{count[$1]++}END{for(j in count) print j,""count[j]""}'
如果输入是:
A horse pen
A dog apple
B cat house
C mouse grape
C mouse shoe
C elephant pole
输出将是:
A 2 dog apple
B 1 cat house
C 3 elephant pole
答案 0 :(得分:1)
这应该有用,但要注意不保证订单保留
awk '{k=$1; a[k]++; $1="";
sub(/^ +/, "", $0); b[k]=$0};
END{for (k in a) print k, a[k], b[k]}' file.txt
A 2 dog apple
B 1 cat house
C 3 elephant pole
答案 1 :(得分:1)
如果订单对您至关重要,请尝试以下GNU awk
:
awk '{
ary[$1]++; line[$1] = $2 FS $3
}
END {
n = asorti(ary, sorted_ary)
for(i = 1; i <= n; i++) {
print sorted_ary[i], ary[sorted_ary[i]], line[sorted_ary[i]]
}
}' file
$ cat file
A horse pen
A dog apple
B cat house
C mouse grape
C mouse shoe
C elephant pole
$ awk '{
ary[$1]++; line[$1] = $2 FS $3
}
END {
n = asorti(ary, sorted_ary)
for(i = 1; i <= n; i++) {
print sorted_ary[i], ary[sorted_ary[i]], line[sorted_ary[i]]
}
}' file
A 2 dog apple
B 1 cat house
C 3 elephant pole