如何使用bash总结每一列在一个文件中 [英] how to sum each column in a file using bash
本文介绍了如何使用bash总结每一列在一个文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下格式的文件
id_1,1,0,2,3,lable1
id_2,3,2,2,1,lable1
id_3,5,1,7,6,lable1
和我想每一列(我有超过300列)
and I want the summation of each column ( I have over 300 columns)
9,3,11,10,lable1
我怎么能做到这一点使用bash。
我试着用什么这里描述,但没有奏效。
how can I do that using bash. I tried using what described here but didn't work.
推荐答案
如果总计将需要在最后一列标签进行分组,你可以试试这个:
If the totals would need to be grouped by the label in the last column, you could try this:
awk -F, '
{
L[$NF]
for(i=2; i<NF; i++) T[$NF,i]+=$i
}
END{
for(i in L){
s=i
for(j=NF-1; j>1; j--) s=T[i,j] FS s
print s
}
}
' file
如果在最后一列标签进行排序,那么你可以尝试没有数组和节省内存:
If the labels in the last column are sorted then you could try without arrays and save memory:
awk -F, '
function labelsum(){
s=p
for(i=NF-1; i>1; i--) s=T[i] FS s
print s
split(x,T)
}
p!=$NF{
if(p) labelsum()
p=$NF
}
{
for(i=2; i<NF; i++) T[i]+=$i
}
END {
labelsum()
}
' file
这篇关于如何使用bash总结每一列在一个文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文