awk – calculation of sums of rows and columns

awk command in a bash script

#!/bin/bash 
myfile="myfile.dat"
cat $myfile
echo

echo -e "\nRow sum: method 1"
awk 'BEGIN{j=1;}{
for (i=1; i<=NF; i++) 
rowsum[j]+=$i; 
j++;
};
END{
for (k in rowsum)
print "the sum of row "k" is " rowsum[k];
}' $myfile

echo -e "\nColumn sum: method 1"
awk 'BEGIN{;}{
for (i=1; i<=NF;i++) 
colsum[i]+=$i;}; 
END{
for (k in colsum) print "the sum of column "k" is " colsum[k];
}' $myfile

 

mydata.dat file

124 127 130
112 142 135
175 158 245
118 231 147

About albertsk

Professor at the University of Hawaii
This entry was posted in Uncategorized. Bookmark the permalink.