34

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.

Alex B
  • 4,478

3 Answers3

36

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
Glorfindel
  • 815
  • 2
  • 10
  • 19
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:

Ciro Santilli OurBigBook.com
  • 18,092
  • 4
  • 117
  • 102
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.

agc
  • 7,223