2

I need to sum numbers located in a file like this one:

      column1  column2 column3
row1  a(1,1)   a(1,2)  a(1,3)
row2  a(2,1)   a(2,2)  a(2,3)
row3  a(3,1)   a(3,2)  a(3,3)
row4  a(4,1)   a(4,2)  a(4,3)


      column4  column5 column6
row1  b(1,1)   b(1,2)  b(1,3)
row2  b(2,1)   b(2,2)  b(2,3)
row3  b(3,1)   b(3,2)  b(3,3)
row4  b(4,1)   b(4,2)  b(4,3)

      column7  column8 column9
row1  c(1,1)   c(1,2)  c(1,3)
row2  c(2,1)   c(2,2)  c(2,3)
row3  c(3,1)   c(3,2)  c(3,3)
row4  c(4,1)   c(4,2)  c(4,3)

and to output a thing like that:

   column1    a(1,1)+a(2,1)       a(3,1)+a(4,1)  
   column2    a(1,2)+a(2,2)       a(3,2)+a(4,2)
   column3    a(1,3)+a(2,3)       a(3,3)+a(4,3)
   column4    b(1,1)+b(2,1)       b(3,1)+b(4,1)
   column5    b(1,2)+b(2,2)       b(3,2)+b(4,2)
   column6    b(1,3)+b(2,3)       b(3,3)+b(4,3)
   column7    c(1,1)+c(2,1)       c(3,1)+c(4,1)
   column8    c(1,2)+c(2,2)       c(3,2)+c(4,2)   
   column9    c(1,3)+c(2,3)       c(3,3)+c(4,3)

I have one way to do that in bash, but it only functions with two 2D-arrays and fails with this example, which contains three 2D arrays. I want something that could be useful to many 2D arrays. Here the script that only functions for two 2D arrays.

   sed 's/row[1-6]//;/^$/d' test |   
   pr -2t |
   awk 'NR==1{$1=$1; print; next}
   !(NR%2){split($0,a); next}
         {for(i=1;i<=NF;i++) $i+=a[i]}1' |
    tr ' ' '\n' |
  pr -3t

Note: to compute the sums replace cell indices with values with this:

       $ tr -d 'ab(,)' < file > filenums
1

I suppose the trick is to use -3t for the first pr, and then also add -w200 (or so) to avoid that the last column gets clipped.

More generally, if you have N matrices, you'd use pr -${N}t -w $((N*W)) as first pr command, where W is the character width of the one matrix (say, roughly 10 for each column plus a bit).

All else should be fine.

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.