Created
June 28, 2014 10:58
-
-
Save uobikiemukot/af0e8a9800aa124478dd to your computer and use it in GitHub Desktop.
"double lines" version of holman/spark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# | |
# spark | |
# https://github.com/holman/spark | |
# | |
# Generates sparklines for a set of data. | |
# | |
# Here's a a good web-based sparkline generator that was a bit of inspiration | |
# for spark: | |
# | |
# https://datacollective.org/sparkblocks | |
# | |
# spark takes a comma-separated list of data and then prints a sparkline out of | |
# it. | |
# | |
# Examples: | |
# | |
# spark 1 5 22 13 53 | |
# # => ▁▁▃▂▇ | |
# | |
# spark 0 30 55 80 33 150 | |
# # => ▁▂▃▅▂▇ | |
# | |
# spark -h | |
# # => Prints the spark help text. | |
# Generates sparklines. | |
# | |
# $1 - The data we'd like to graph. | |
_echo() | |
{ | |
if [ "X$1" = "X-n" ]; then | |
shift | |
printf "%s" "$*" | |
elif [ -z "$1" ]; then | |
printf " " | |
else | |
printf "%s\n" "$*" | |
fi | |
} | |
spark() | |
{ | |
local n numbers= | |
# find min/max values | |
local min=0xffffffff max=0 | |
for n in ${@//,/ } | |
do | |
# on Linux (or with bash4) we could use `printf %.0f $n` here to | |
# round the number but that doesn't work on OS X (bash3) nor does | |
# `awk '{printf "%.0f",$1}' <<< $n` work, so just cut it off | |
n=${n%.*} | |
(( n < min )) && min=$n | |
(( n > max )) && max=$n | |
numbers=$numbers${numbers:+ }$n | |
done | |
# print ticks (use 2 lines) | |
IFS_ORIG="$IFS" | |
tickstr1=$' , , , , , , , ,▁,▂,▃,▄,▅,▆,▇,█' | |
tickstr2=$'▁,▂,▃,▄,▅,▆,▇,█,█,█,█,█,█,█,█,█' | |
IFS=, | |
local ticks1=($tickstr1) | |
local ticks2=($tickstr2) | |
IFS="$IFS_ORIG" | |
local f=$(( (($max-$min)<<8)/(${#ticks1[@]}-1) )) | |
(( f < 1 )) && f=1 | |
for n in $numbers | |
do | |
_echo -n "${ticks1[$(( ((($n-$min)<<8)/$f) ))]}" | |
done | |
echo | |
for n in $numbers | |
do | |
_echo -n ${ticks2[$(( ((($n-$min)<<8)/$f) ))]} | |
done | |
echo | |
} | |
# If we're being sourced, don't worry about such things | |
if [ "$BASH_SOURCE" == "$0" ]; then | |
# Prints the help text for spark. | |
help() | |
{ | |
cat <<EOF | |
USAGE: | |
spark [-h|--help] VALUE,... | |
EXAMPLES: | |
spark 1 5 22 13 53 | |
▁▁▃▂█ | |
spark 0,30,55,80,33,150 | |
▁▂▃▄▂█ | |
echo 9 13 5 17 1 | spark | |
▄▆▂█▁ | |
EOF | |
} | |
# show help for no arguments if stdin is a terminal | |
if { [ -z "$1" ] && [ -t 0 ] ; } || [ "$1" == '-h' ] || [ "$1" == '--help' ] | |
then | |
help | |
exit 0 | |
fi | |
spark ${@:-`cat`} | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment