columnize 844 Bytes
Newer Older
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
#!/bin/bash
# columnize.sh
# Take a list of values and output them in a nicely formatted column view.
# Author: Loïc Cattani "Arko" <loic cattani at gmail com>
# https://github.com/Arko/Columnize

values=($*)
longest_value=0

# Find the longest value
for value in ${values[@]}; do
	if [[ ${#value} -gt $longest_value ]]; then
		longest_value=${#value}
	fi
done

# Compute column span
term_width=${COLUMNS:-$(tput cols)}
(( columns = $term_width / ($longest_value + 2) ))

# Print values with pretty column width
curr_col=0
for value in ${values[@]}; do
	value_len=${#value}
	echo -n $value
	(( spaces_missing = $longest_value - $value_len + 2 ))
	printf "%*s" $spaces_missing
	(( curr_col++ ))
	if [[ $curr_col == $columns ]]; then
		echo
		curr_col=0
	fi
done

# Make sure there is a newline at the end
if [[ $curr_col != 0 ]]; then echo; fi