]> zdv2.bktei.com Git - BK-2020-03.git/blob - unitproc/bkt-sum_float
fix(unitproc/bkt-sum_float):Simplify
[BK-2020-03.git] / unitproc / bkt-sum_float
1 #!/bin/bash
2 # Desc: Sums newline-delimited floats received from stdin
3 # Usage: some_app | sumFloat
4 # Example: printf -- "-3\n0.14" | sumFloat
5 # Result: -2.860000
6 # Version: 0.0.2
7 # Depends: bc 1.07.1
8
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
12 sum_float() {
13 # Desc: Sums newline-delimited floats received on stdin
14 # Usage: some_app | sum_float
15 # Depends: bc 1.07.1, paste (GNU coreutils)
16
17 # Check dependencies
18 command -v bc 1>/dev/random 2>&1 || { dief "FATAL:Missing:bc"; };
19 [[ ! -t 0 ]] || { dief "FATAL:No stdin detected."; };
20
21 # Process lines
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}"; };
27 nums+=("$line");
28 done;
29
30 # Print output
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)";
33 } # sum stdin floats
34
35 # Author: Steven Baltakatei Sandoval
36 # License: GPLv3+