How to align columns in output from a UNIX command?
Matthew Harrington
I used to know of a command -- an actual command mind you, not sed/awk magic -- that formatted its input to be aligned in columns. For example, if you ran:
% echo -e "aaaaa bbbbbbb\ncc ddd"
aaaaa bbbbbbb
cc dddBut if you ran the output through the command which I've forgotten the name of:
% echo -e "aaaaa bbbbbbb\ncc ddd" | mystery_command
aaaaa bbbbbbb
cc dddDoes anyone know the name of that command?
02 Answers
It's column. Try for example echo -e "aaaaa bbbbbbb\ncc ddd" | column -t.
awk solution that deals with stdin
Since column is not POSIX, maybe this is:
mycolumn() ( file="${1:--}" if [ "$file" = - ]; then file="$(mktemp)" cat >"${file}" fi awk ' FNR == 1 { if (NR == FNR) next } NR == FNR { for (i = 1; i <= NF; i++) { l = length($i) if (w[i] < l) w[i] = l } next } { for (i = 1; i <= NF; i++) printf "%*s", w[i] + (i > 1 ? 1 : 0), $i print "" } ' "$file" "$file" if [ "$file" = - ]; then rm "$file" fi
)Test:
printf '12 1234 1
12345678 1 123
1234 123456 123456
' > fileTest commands:
mycolumn file
mycolumn <file
mycolumn - <fileOutput for all:
12 1234 1
12345678 1 123 1234 123456 123456See also:
1