# How to sum specific rows of a matrix

I need to sum the matrix elements of specific rows for each column. An example of the matrix is given below(input). So the matrix has 4 columns and 6 rows of numbers. I need to sum the numbers of specific rows for each column. I other words I need to sum the elements of row1 + row2 + row5 and row3 + row4 + row6 for each column.

Input :

``````   column1  column2 column3 column4
11.1     12       13     4
21.3     22       23     3
31       32       33    45
41       42       43   536
23       32        6     5
4        5        3     2
``````

The output should looks like this.

``````  column1 column2 column3 column4
55.4    66      42      12
76      79      79     583
``````

I was trying to use `awk` like this:

``````awk 'NR==1{\$1=\$1; print; next} !(NR%2){split(\$0,a); next} {for(i=1;i<=NF;i++) \$i+=a[i]}1' file
``````

but I cannot get the expected result.

• Do you really need to do it in bash specifically, as per your title? Doing math in sed, as you have tagged, is tricky. Is awk acceptable? Jun 2, 2016 at 12:56
• @alloppp, please show your work so far and we can help correct any mistakes. Jun 2, 2016 at 12:58
• must use `awk` or another tool to sum up floats as `bash` doesn't handle floats Jun 2, 2016 at 13:02
• @glennjackman I only can make the sum of the consecutive rows , see it : awk 'NR==1{\$1=\$1; print; next} !(NR%2){split(\$0,a); next} {for(i=1;i<=NF;i++) \$i+=a[i]}1' file Jun 2, 2016 at 13:03
• alloppp use the edit link to update your post Jun 2, 2016 at 13:04

KISS implementation in `awk`:

``````awk '
FNR == 1 {
n=NF;print;next
}
FNR == 2 || FNR == 3 || FNR == 6 {
for (i=1;i<=NF;i++) a[i]+=\$i;
}
FNR == 4 || FNR == 5 || FNR == 7 {
for (i=1;i<=NF;i++) b[i]+=\$i
} END {
for (i=1;i<=n;i++) printf("%8s", a[i]); print "";
for (i=1;i<=n;i++) printf("%8s", b[i]); print "";
}
' file
``````
• Might as well use `i<=n` in the loops setting "a" and "b" arrays. Jun 2, 2016 at 13:46
• +1. `FNR ~ /^(2|3|6)\$/ { ... }` etc also works and is less tedious than typing lots of `|| FNR == `comparisons.
– cas
Jun 3, 2016 at 0:12