Bash – Summing rows in a new column using sed, awk and perl

awkbashperlsed

I have a file that contain numbers something like:

1 11 323
2 13 3
3 44 4
4 66 23
5 70 23
6 34 23
7 24 22
8 27 5

How can I sum the rows and output the results in a column, so the results are as follows:

1 11 323 335
2 13 3 18
3 44 4 51
4 66 23 93
5 70 23 98
6 34 23 63
7 24 22 53
8 27 5 40

I would like to see solutions in sed, awk, and perl

Best Answer

Perl solution:

perl -MList::Util=sum -lane 'print "@F ", sum(@F)' < data.txt
  • -n reads the input line by line
  • -l removes newlines from input and adds them to output
  • -a splits each input line on whitespace into the @F array
  • List::Util provides the sum function so you don't have to sum the numbers yourself

In sed, arithmetic is nearly impossible to implement, but you can use sed to turn spaces into pluses and use that as a source for bc to get the sums, and paste the results with the input:

paste -d ' ' data.txt <(sed -r 's/ /+/g' data.txt | bc)
Related Question