sorting - 对大数据文件进行排序和求和

标签 sorting awk uniq

我必须处理一个 sort 似乎无法处理的文件。 这些文件大约是。每个 3 GB。

输入内容如下:

last-j  nmod+j+n    year-n 9492
last-j  nmod+j+n    night-n 8075
first-j nmod+j+n-the    time-n 7749
same-j  nmod+j+n-the    time-n 7530
other-j nmod+j+n-the    hand-n 5319
ast-j   nmod+j+n   year-n 1000
last-j   nmod+j+n   night-n 5000
first-j   nmod+j+n-the   time-n 1000
same-j   nmod+j+n-the   time-n 3000
other-j   nmod+j+n-the   hand-n 200

其中我需要对相应重复项的数量进行求和。

因此所需的输出如下:

   last-j   nmod+j+n    year-n 10492
    last-j  nmod+j+n    night-n 13075
    first-j nmod+j+n-the    time-n 8749
    same-j  nmod+j+n-the    time-n 10530
    other-j nmod+j+n-the    hand-n 5519

我一直在尝试这个排序命令,应该可以解决问题

sort input | uniq -c | awk '{print $2 "\t" $3 "\t" $1*$4}' 

内存不足。对于可以更优化以处理更大的数据文件的东西有什么建议吗?谢谢

最佳答案

awk中使用数组,您可以一起完成所有操作,无需排序uniq:

$ awk '{a[$1,$2,$3]+=$4} END{for (i in a) print i, a[i]}' file
first-jnmod+j+n-thetime-n 8749
ast-jnmod+j+nyear-n 1000
same-jnmod+j+n-thetime-n 10530
last-jnmod+j+nnight-n 13075
last-jnmod+j+nyear-n 9492
other-jnmod+j+n-thehand-n 5519

由于这是使用第1、2、3列作为索引,所以它们都写在一起。这可以通过将它们放在另一个数组中来解决:

$ awk '{a[$1,$2,$3]+=$4; b[$1,$2,$3]=$1" "$2" "$3} END{for (i in a) print b[i], a[i]}' a
first-j nmod+j+n-the time-n 8749
ast-j nmod+j+n year-n 1000
same-j nmod+j+n-the time-n 10530
last-j nmod+j+n night-n 13075
last-j nmod+j+n year-n 9492
other-j nmod+j+n-the hand-n 5519

关于sorting - 对大数据文件进行排序和求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19832626/

相关文章:

regex - 使用linux查找和替换

java - 在给定内存限制的情况下对具有大量数据的文件进行排序

jquery - 使用jquery求和div内元素的值

list - 对列表应用自定义排序(对列表列表进行排序)

bash - 使用键值连接两个 csv 文件

string - AWK:打印列变量,每个字符用空格分隔

c# - C# 中的自然排序顺序

linux - 有没有办法按列 'uniq'?

utf-8 - 如何强制唯一区分全破折号和短破折号?

bash - 实时 stdout 的输出重定向在将其通过管道传输到 uniq 或 awk 后不起作用