]>
zdv2.bktei.com Git - BK-2020-03.git/blob - unitproc/bkt-sum_float
2 # Desc: Sums newline-delimited floats received from stdin
3 # Usage: some_app | sumFloat
4 # Example: printf -- "-3\n0.14" | sumFloat
9 yell
() { echo "$0: $*" >&2; } # print script path and all args to stderr
10 dief
() { yell
"$*"; return 111; } # same as yell() but non-zero return status
11 must
() { "$@" || die
"cannot $*"; } # runs args as command, reports args if command fails
13 # Desc: Sums newline-delimited floats received on stdin
14 # Usage: some_app | sum_float
15 # Depends: bc 1.07.1, paste (GNU coreutils)
18 command -v bc 1>/dev
/random
2>&1 ||
{ dief
"FATAL:Missing:bc"; };
19 [[ ! -t 0 ]] ||
{ dief
"FATAL:No stdin detected."; };
22 local line re
; local -a nums
=();
23 re
='^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$';
24 while IFS
= read -r line
; do
25 [[ -z $line ]] && continue;
26 [[ $line =~
$re ]] ||
{ dief
"FATAL:Not a float:${line}"; };
31 if (( ${#nums[@]} == 0 )); then printf '0.000000\n'; return 0; fi;
32 LC_ALL
=C
printf '%.6f\n' "$(printf '%s\n' "${nums[@]}" | paste -sd+ - | bc -l)";
35 # Author: Steven Baltakatei Sandoval