Reputation: 141
I have a file that contains data like this:
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)
I need to sum the elements of the array to show an output like this the output
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)
I though that a way to do this is to specify the position of each number and them sum , but I have no idea how to do that.
Upvotes: 0
Views: 171
Reputation: 51
You can create multidimensional array something like this
awk 'BEGIN{i=0}{i++;r[i][0];split($0,r[i]," ");}END{print r[1][1]+r[2][1] #do your math here}' filename
Upvotes: 1
Reputation: 67507
dance of the pipes
$ sed 's/row[0-9]//;/^$/d' filenums |
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
column1 32 72
column2 34 74
column3 36 76
column4 32 72
column5 34 74
column6 36 76
to compute the sums I replaced cell indices with values with this
$ tr -d 'ab(,)' < file > filenums
so a(1,1) became 11, etc.
Upvotes: 1