summaryrefslogtreecommitdiff
path: root/sum3.awk
blob: 7f11a49c71080f0e017281b8c27c043cee0d5972 (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
#!/usr/bin/awk -f

### sum3.awk, print sums of numeric columns
# input:    rows of integers and strings
# output:   sums of numeric columns
#   assumes every line has same layout


function isnum(n) {
    return n ~ /^[+-]?[0-9]+$/
}


BEGIN {
    OFS = FS
}


NR == 1 {
    for (i=1; i<=NF; i++)
        numcol[i] = isnum($i)
}


NF > 0 {
    (NF > nf_max) ? nf_max = NF : nf_max = nf_max
    for (i=1; i<=NF; i++)
        if (numcol[i])
            sum[i] += $i
}


END {
    for (i=1; i<=nf_max; i++) {
        printf(numcol[i] ? sum[i] : "--")
        printf(i < nf_max ? OFS : ORS)
    }
}