sed (or awk) to sum values in a csv file

为君一笑 提交于 2020-01-24 13:08:07

问题


I have a csv file where the lines look like this:

foo,bar,baz,5,6,8
zab,rab,oof,2,2,3

I need a command to transform it summing the last 3 values:

foo,bar,baz,19
zab,rab,oof,7

If possible I need a one liner.


回答1:


Try this for fixed length :

awk -F, '{print $1,$2,$3,$4+$5+$6}' OFS=, file

And for not fixed length :

awk -F, '{for(i=1;i<NF-2;i++)printf("%s,", $i)}{print $NF+$(NF-1)+$(NF-2)}' file

sed is not the right tool for arithmetic.




回答2:


perl -F, -lane '$a+=$_ for(@F[3..5]);print join ",",@F[0..2],$a' your_file

small test below:

> echo "foo,bar,baz,5,6,8" | perl -F, -lane '$a+=$_ for(@F[3..5]);print join ",",@F[0..2],$a'
foo,bar,baz,19


来源:https://stackoverflow.com/questions/15548771/sed-or-awk-to-sum-values-in-a-csv-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!