How to output an array's content in columns in BASH
You could pipe your output to column
.
column
seems to struggle with some data in a single-column input being narrower than a tabstop (8 characters).
Using printf
within a for
-loop to pad values to 8 characters seems to do the trick:
for value in "${values[@]}"; do
printf "%-8s\n" "${value}"
done | column
Here are a couple of techniques that can be used with Johnsyweb's answer so you can do your output without a loop:
saveIFS=$IFS
IFS=$'\n'
echo "${values[*]}" | column
IFS=$saveIFS
or
echo " ${arr[@]/%/$'\n'}" | column
or
echo " ${arr[@]/%/$'\n'}" | sed 's/^ //' | column
I know this is an old thread, but I get erratic results from column so I thought I'd give my solution. I wanted to group every 3 lines into 3 evenly spaced columns.
cat file.txt | xargs printf '%-24s\n' | sed '$p;N;s/\n//;$p;N;s/\n//'
Basically, it pipes each line into printf, which left-aligns it into a 24-character-wide block of whitespace, which is then piped into sed. sed will look ahead 2 lines into the future and remove the line break.
The N command reads the next line into the current buffer, and s/\n// removes the line break. In short, what we want is 'N;N;s/\n//g', which will work in some cases. The problem is, if there aren't two extra lines to throw in the buffer, sed will quit suddenly. The $p commands pre-empt that by saying "If this is the last line, print the buffer contents immediately".