-
Notifications
You must be signed in to change notification settings - Fork 2
/
barchart
executable file
·55 lines (53 loc) · 1.52 KB
/
barchart
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
#!/bin/sh
char=#
[ -r /dev/tty ] && cols=$(stty </dev/tty size 2>/dev/null | awk '{print $2}')
[ -n "$cols" ] || cols=80
while [ 0 -lt "$#" ]; do
opt="$1"
case "$opt" in
-c) shift; char="$1" ;;
-c*) char="${1##-c}" ;;
-w) shift; cols="$1" ;;
-w*) cols="${1##-w}" ;;
-v) echo 'barchart version 1.0.5'; exit 0 ;;
-h) cat <<EOT ; exit 0 ;;
Usage: barchart [-w cols] [-c char] [-h] [-v] [--] file...
Makes a bar chart from input files, or standard input if no files are given.
Options:
-w cols Force bar chart width to the given columns. Without this, the program
tries to use the controlling terminal width.
-c char Make bars out of the given character.
-h Print this help.
-v Print version.
Each input line is a non-negative integer followed by an optional label.
EOT
--) shift; break ;;
-?*) echo >&2 "$0: Invalid option: $opt"; exit 1 ;;
*) break ;;
esac
[ 0 -lt "$#" ] || {
echo >&2 "$0: Option $opt requires an argument"
exit 1
}
shift
done
exec awk -v char="$char" -v cols="$cols" '
{ count = +$1;
$1 = "";
label = substr($0, 2);
sum += count;
if (count > max) max = count;
l = length(""count);
if (l > countlen) countlen = l;
l = length(label);
if (l > labellen) labellen = l;
counts[+n] = count;
labels[+n] = label;
++n }
END { width = cols - countlen - 1 - labellen - 1;
for (i = 0; i < +n; ++i) {
printf "%"countlen"d %-"labellen"s ", counts[i], labels[i];
if (max > width) counts[i] = counts[i] / max * width;
while (counts[i]-- > 0) printf "%s", char;
printf "\n";
} }' "$@"