This repository has been archived by the owner on Aug 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsumallcol
executable file
·57 lines (50 loc) · 1.81 KB
/
sumallcol
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
50
51
52
53
54
55
56
#!/usr/bin/awk -f
# The script will dynamically determine the schema of the table by examining the first
# or second record (a line) - if the first one is the header.
# If there is different number of fields (a columns) in folowing records,
# all that exceded are just ignored, and if there is less then set,
# script will sum them from the left most.
# So for corect results, use clean data.
# It check if value is numeric (float, fraction or integer)
# and then prevent from counting character strings onto final result.
function is_num(n) {
sign = "[+-]?"
decimal = "[0-9]+[.]?[0-9]"
digit = "[0-9]"
fraction = "[.][0-9]"
number = "^" sign "(" decimal "|" fraction "|" digit ")" "+$"
return (n ~ number) # ^[+-]?([0-9]+[.]?[0-9]|[.][0-9]|[0-9])+$
}
NR==1 {
while (i<=NF) {
p = is_num($i); # if all fields are character, this record is heading
hnum = hnum + p; # regex returns 0 for strings
i++ }
start = (hnum >= 1)? 1: 2; # start counting NR after heading
}
NR==start {
nfld = NF # preserve for END
for (i=1; i <= NF; i++)
numcol[i] = is_num($i) # mark if is number
}
{
for (i=1; i <= NF; i++)
if (numcol[i]) # If is number
sum[i] += $i # add to sum for apropriate column.
}
END {
for (i=1; i <= nfld; i++) {
if (numcol[i])
printf("%g", sum[i])
else
printf("--")
printf(i < nfld ? "\t" : "\n")
}
}
# The idea, this one-liner can't handle irregularities like a
# random character in a column or count all fields at once.
# $ awk -F'\t' '{num = num + $2} END{print num}' co.tsv
# 25681
# ******************************
# $ cat test/trashcolumns.txt | awk -f sumcol.awk
# -- 1 -0.9179