summaryrefslogtreecommitdiff
path: root/sum4.awk
blob: 3e61843f5afb5b9ef3f05066e2bbfd131877ada7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/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 {
    for (i=1; i<=NF; i++)
        isnum($i) ? header[i] = "col" i : header[i] = $i
}


NF > 0 {
    (NF > nf_max) ? nf_max = NF : nf_max = nf_max
    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)
    }
}