33

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.

35

Use column -t. column is part of util-linux.

$ 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:

0

For relatively small files, (where the length in bytes is less than getconf ARG_MAX), and the input sizes are more or less known, (let's say no fruit name is more than 18 letters long), printf can be useful, here's a bash example:

 printf '%-20s %5s %5s\n' $(<file.txt)

Output:

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

Note how the numbers are right justified.

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.