#!/bin/bash print_help(){ echo "Create an ASCII barchart with key-value pair from a TSV file." echo "Usage $0 [KEY_COL_NUM] [VALUE_COL_NUM]" } # print help if requested or check if exists if [[ "$1" == "-h" ]]; then print_help else [[ ! -f "$1" ]] && echo "$1 is not a valid file!" && exit tsv_file="$1" fi # get KEY_COL_NUM and VALUE_COL_NUM num_re='([0-9]+)' [[ "$2" =~ $num_re ]] [[ "$2" == "${BASH_REMATCH[1]}" ]] && [[ "$2" != "" ]] && KEY_COL_NUM="$2" || KEY_COL_NUM="1" [[ "$3" =~ $num_re ]] [[ "$3" == "${BASH_REMATCH[1]}" ]] && [[ "$2" != "" ]] && VALUE_COL_NUM="$2" || VALUE_COL_NUM="2" # get MAX_KEY_LENGTH and MAX_VALUE MAX_KEY_LENGTH=1 MAX_VALUE=0 while read line; do key=$(echo "$line" | cut -f "$KEY_COL_NUM" ) value=$(echo "$line" | cut -f "$VALUE_COL_NUM" ) [ $MAX_KEY_LENGTH -lt "${#key}" ] && MAX_KEY_LENGTH="${#key}" [ $MAX_VALUE -lt "$value" ] && MAX_VALUE="$value" done < $tsv_file # print the barchart bar="█" MAX_BARS=60 while read line; do key=$(echo "$line" | cut -f "$KEY_COL_NUM" ) value=$(echo "$line" | cut -f "$VALUE_COL_NUM" ) barvalue=$(( value*MAX_BARS/MAX_VALUE )) printf "%-${MAX_KEY_LENGTH}s " "$key" for (( i=1;i<=$barvalue;i++ )); do printf "%s" "$bar" done printf " %d\n" "$value" done < $tsv_file