#!/bin/sh # The MIT License (MIT) # # Copyright © 2024 pacman64 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the “Software”), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # sn [filepaths...] # # Summarize Numbers does what it says, using all numbers detected from the # input(s). When given no filepaths, it reads from standard input. # handle help options case "$1" in -h|--h|-help|--help) awk '/^# +sn/, /^$/ { gsub(/^# ?/, ""); print }' "$0" exit 0 ;; esac awk ' # initialize stats BEGIN { inf = "+inf" + 0 min = inf max = -inf count = 0 sum = 0 mean = 0 prod = 1 ints = 0 pos = 0 zero = 0 neg = 0 } # update stats using all detected numbers from every line { for (i = 1; i <= NF; i++) { s = $i if (s == "" || s ~ / +/ || s ~ /[^0-9.-]/) { continue } v = s + 0 if (s !~ /\./ || s ~ /\.0*$/) { ints++ } count++ min = min < v ? min : v max = max > v ? max : v sum += v prod *= v lnSum += v <= 0 ? nan : log(v) if (v > 0) { pos++ } else if (v < 0) { neg++ } else if (v == 0) { zero++ } # advance welford`s algorithm d1 = v - mean mean += d1 / count d2 = v - mean meanSq += d1 * d2 } } # report final numeric stats END { #sum = mean * count # separate name-value pairs using tabs, and prepare a # pipeable command which ignores all-zero decimals OFS = "\t" # pipe all output lines into the special command, even # when it is seemingly unneeded due to integer values, # since not doing so can scramble the final order of # the output lines print "numeric", count print "min", sprintf("%f", min) print "max", sprintf("%f", max) print "sum", sprintf("%f", sum) print "mean", sprintf("%f", mean) if (lnSum != -inf && count > 0) { geomean = exp(lnSum / count) print "geomean", sprintf("%f", geomean) } else { print "geomean", "" } if (count > 0) { sd = sqrt(meanSq / count) print "sd", sprintf("%f", sd) #print "product", prod print "product", sprintf("%g", prod) } else { print "sd", "" print "product", "" } print "integer", ints print "positive", pos print "zero", zero print "negative", neg } ' "$@" | sed 's-\\.00*$--'