Nod
Honorary Master
- Joined
- Jul 22, 2005
- Messages
- 10,057
If you have a file with numerical columns, and need a total of each column, it would be easy to do the calculation with awk.
Given the input file with contents:
Execute the command like this:
you'll get the following output:
By adding
to the command, we get.
The source of the awk script:
Found the awk script here: http://stackoverflow.com/questions/...lculate-the-sum-of-a-column-of-output-on-unix
Given the input file with contents:
Code:
server1 2 4 5 2 1 5
server2 4 5 6 7 2 7
Code:
cat <filename> | addco.sh
Code:
0 6 9 11 9 3 12
Code:
|sed "s/^ 0/Total\:/g"
Code:
Total: 6 9 11 9 3 12
The source of the awk script:
Code:
#!/usr/bin/awk -f
# Sum up numerical values by column (white-space separated)
#
# Usage: $0 [file ...]
#
# stern, 1999-2005
{
for(i = 1; i <= NF; ++i) {
scale = 1
if ($i ~ /[kK]$/) { scale = 1000 }
if ($i ~ /[mM]$/) { scale = 1000*1000 }
if ($i ~ /[gG]$/) { scale = 1000*1000*1000 }
col[i] += scale * $i;
}
if (NF > maxnf) maxnf = NF;
}
END {
for(i = 1; i <= maxnf; ++i) { printf " %.10g", col[i] }
print "";
}