问题
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