Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

How to align columns in output from a UNIX command?

Writer 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 ddd

But 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 ddd

Does anyone know the name of that command?

0

2 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
' > file

Test commands:

mycolumn file
mycolumn <file
mycolumn - <file

Output for all:

 12 1234 1
12345678 1 123 1234 123456 123456

See also:

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy