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

### sum_col.awk
# sum columns of numerical data
# input: delimited data as text
# output: list of univariate summary stats


BEGIN {
    OFS = FS
    sign = "[+-]?"
    decimal = "[0-9]+[.]?[0-9]*"
    fraction = "[.][0-9]+"
    exponent = "([Ee]" sign "[0-9]+)?"
    number = "^" sign "(" decimal "|" fraction ")" exponent "$"
}


# read column headers
NR == 1 {
    for (n=1; n<=NF; n++)
        ($n ~ number) ? header[n] = "col" n : header[n] = $n
}


# iterate over columns
NF > 0 {
    (NF > nf_max) ? nf_max = NF : nf_max = nf_max
    for (n=1; n <= NF; n++) {
        if ($n ~ number) {
            count[n] += 1
            sum[n] += $n
        }
    }
}


END {
    print "col", "sum", "count"
    for (n=1; n<=nf_max; n++) {
        if (header[n])
            print header[n], sum[n], count[n]
        else
            print "col" n, sum[n], count[n]
    }
}