1

I have large and many tables of numbers. Below is just a sample:

A 25 27 50 
B 35 37 75 
C 75 78 80 
D 99 88 76 

I want to sum the rows and the columns in each table for further processing so the output look like this:

A 25 27 50 102
B 35 37 75 147
C 75 78 80 233
D 99 88 76 263
234 230 281

How can I do it? I tried awk but did not work.

1

In general case you would need to do:

awk '{
    for (i=2; i<=NF; i++) {
        sumcols[i]+= $i; sumrows+= $i 
    }; print $0, sumrows
}
END { for (x in sumcols)
         { printf SEP sumcols[x]; SEP=FS };
     print ""
}' infile

The sumcols[i]+= $i part is summing-up the field's value in same column position; and sumrows+= $i is doing the sum in same rows position, then rows print after every line read with print $0, sumrows;

and at the END loop over the sumcols array and use printf to print in single line. The SEP is setting with the value of default Field Separator for second print to the next in order to add a single space between each.

0

You can try this command :

awk '{sum2+=$2; sum3+=$3; sum4+=$4} END {print sum2,sum3,sum4}''{print $0, $2+$3+$4}' file
A 25 27 50 102
B 35 37 75 147
C 75 78 80 233
D 99 88 76 263
234 230 281

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.