这适用于任何给定数量的文件:
$ cat a.cnt b.cnt | awk '{a[$2]+=$1} END{for (i in a) print a[i],i}'
1 a
2 b
3 c
因此,假设您有 10 个文件,您只需要执行cat f1 f2 ...,然后通过管道传输此awk。
如果文件名恰好共享一个模式,您也可以这样做 (thanks Adrian Frühwirth!):
awk '{a[$2]+=$1} END{for (i in a) print a[i],i}' *cnt
例如,这将考虑扩展名为cnt的所有文件。
可能需要另外考虑的一些方面:
- 如果 a、b、c 是任意字符串,包含任意空格怎么办?
- 如果文件太大而无法放入内存怎么办?对于这种情况,是否有一些
sort | uniq -c 样式的命令行选项一次只查看两行?
在这种情况下,您可以将其余列用作计数器的索引:
awk '{count=$1; $1=""; a[$0]+=count} END{for (i in a) print a[i],i}' *cnt
请注意,实际上您不需要sort | uniq -c 并重定向到cnt 文件然后执行重新计数。您可以通过以下方式完成所有操作:
awk '{a[$0]++} END{for (i in a) print a[i], i}' file
示例
$ cat a.cnt
1 and some
2 text here
$ cat b.cnt
4 and some
4 and other things
2 text here
9 blabla
$ cat *cnt | awk '{count=$1; $1=""; a[$0]+=count} END{for (i in a) print a[i],i}'
4 text here
9 blabla
4 and some
4 and other things
关于第二条评论:
$ cat b
and some
text here
and some
and other things
text here
blabla
$ awk '{a[$0]++} END{for (i in a) print a[i], i}' b
2 and some
2 text here
1 and other things
1 blabla