#!/usr/bin/awk -f ### sum4.awk, print sums of numeric columns # input: rows of integers and strings # output: sums of numeric columns function isnum(n) { sign = "[+-]?" decimal = "[0-9]+[.]?[0-9]*" fraction = "[.][0-9]+" exponent = "([Ee]" sign "[0-9]+)?" number = "^" sign "(" decimal "|" fraction ")" exponent "$" return n ~ number } BEGIN { OFS = FS } NR == 1 { nf_max = NF for (i=1; i<=NF; i++) isnum($i) ? header[i] = "col" i : header[i] = $i } { if (NF > nf_max) nf_max = NF for (i=1; i<=NF; i++) { if ($i == header[i]) continue if (isnum($i)) { count[i]++ sum[i] += $i } } } END { for (i=1; i<=nf_max; i++) { printf((header[i]) ? header[i] OFS : OFS) printf((count[i]) ? count[i] OFS sum[i] : OFS) printf(ORS) } }