来自 shell 的 GROUP BY/SUM [英] GROUP BY/SUM from shell

查看:47
本文介绍了来自 shell 的 GROUP BY/SUM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含如下数据的大文件:

I have a large file containing data like this:

a 23
b 8
a 22
b 1

我希望能够得到这个:

a 45
b 9

我可以先对这个文件进行排序,然后通过扫描一次文件在 Python 中进行排序.这样做的一个好的直接命令行方式是什么?

I can first sort this file and then do it in Python by scanning the file once. What is a good direct command-line way of doing this?

推荐答案

现代 (GNU/Linux) 解决方案,如多年前评论中提到的 ;-) .

The modern (GNU/Linux) solution, as mentioned in comments years ago ;-) .

awk '{
    arr[$1]+=$2
   }
   END {
     for (key in arr) printf("%s	%s
", key, arr[key])
   }' file 
   | sort -k1,1

最初发布的解决方案,基于旧的 Unix sort 选项:

The originally posted solution, based on old Unix sort options:

awk '{
    arr[$1]+=$2
   }
   END {
     for (key in arr) printf("%s	%s
", key, arr[key])
   }' file 
   | sort +0n -1

我希望这会有所帮助.

这篇关于来自 shell 的 GROUP BY/SUM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆