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
|
# Integration: generate a formatted report from data with a here-doc
# template, functions and printf.
cat >sales.csv <<'CSV'
region,item,qty,price
north,widget,10,2.50
south,gadget,3,10.00
north,gadget,1,10.00
east,widget,7,2.50
south,widget,4,2.50
CSV
cents() { # 2.50 -> 250
whole=${1%.*}; frac=${1#*.}
echo $((whole * 100 + ${frac#0}))
}
money() { printf '%d.%02d' $(($1 / 100)) $(($1 % 100)); }
total=0
regions=
{
read -r header
while IFS=, read -r region item qty price; do
c=$(cents "$price")
line=$((qty * c))
total=$((total + line))
eval "r_$region=\$(( \${r_$region:-0} + line ))"
case " $regions " in *" $region "*) ;; *) regions="$regions $region" ;; esac
done
} <sales.csv 2>/dev/null
cat <<REPORT
Sales report
============
$(for r in $regions; do eval "v=\$r_$r"; printf '%-8s %8s\n' "$r" "$(money $v)"; done)
------------
$(printf '%-8s %8s' total "$(money $total)")
REPORT
|