How to align columns in output from a UNIX command?

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?


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:

  • https://stackoverflow.com/questions/14095011/using-awk-to-align-columns-in-text-file
  • https://stackoverflow.com/questions/28544105/awk-go-through-the-file-twice-doing-different-tasks