31

A long time ago I remember using a command that makes its input into a nicely formatted table.

For example, for this input,

apple 1 100
orange 20 19
pineapple 1000 87
avocado 4 30

The output will be similar to this:

apple     1    100
orange    20   19
pineapple 1000 87
avocado   4    30

I'd like to know the name of this tool.

34

column -t

$ column -t <<END
> apple 1 100
> orange 20 19
> pineapple 1000 87
> avocado 4 30
> END
apple      1     100
orange     20    19
pineapple  1000  87
avocado    4     30
  • I like the man page: "columnate lists". Similar to "tablify". – Reid Jul 30 '11 at 22:56
0

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:

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.