Thomas Fischer's Weblog

Life, Linux, LaTeX

Archive for May 2008

Pretty printing LaTeX tables

with one comment

AWK is a really nice tool regarding processing text automatically. Here, I’d like to show you an example how to use AWK to pretty print tables in LaTeX source code.

The AWK script itself is a one-liner. It reads your table from stdin (simply copy&paste to your terminal) and writes the formatted table to stdout. It is assumed that one table row corresponds to one line in the input data. The script checks for the widest cell in each column (number of characters) and aligns the output so that the &s are vertically aligned. The first column will be left-aligned, all other columns are right-aligned.

And here is the script (you can put everything in one line when removing all \):

awk -F '[\\t ]*([&]|\\\\\\\\)[\\t ]*' 'BEGIN { maxcol=0 } \
  { for (i=1; i<=NF; ++i) cell[NR,i]=$i; if (NF-1>maxcol) \
  maxcol=NF-1 } END { for (c=1; c<=maxcol; ++c) { \
  colwidth[c]=0; for (r=1;r<=NR; ++r) if \
  (length(cell[r,c])>colwidth[c]) colwidth[c]= \
  length(cell[r,c]); }; for (r=1; r<=NR; ++r) { printf \
  "%s%"(colwidth[1]-length(cell[r,1]))"s", cell[r,1], ""; \
  for (c=2; c<=maxcol; ++c) printf " & %"colwidth[c]"s", \
  cell[r,c]; print " \\\\" } }'

Finally, a before and after example:

 &1 & 2& 3  & 4&5 &  6 \\
Square & 1  &  4& 9 & 16  & 25& 36         \\
Faculty  & 1 & 2 & 6  &  24 &  120  & 720  \\
Exp  & 2.72 &  7.39  &  20.09 & 54.6  & 148.41 & 403.43  \\
        &    1 &    2 &     3 &    4 &      5 &      6 \\
Square  &    1 &    4 &     9 &   16 &     25 &     36 \\
Faculty &    1 &    2 &     6 &   24 &    120 &    720 \\
Exp     & 2.72 & 7.39 & 20.09 & 54.6 & 148.41 & 403.43 \\

There is also a shell script calling the above AWK script:

Download script

Update: The script has been modified to support multicolumn commands a little bit better.

Update 2 (2009-03-20): In a discussion with Günther, we came up with a real small solution.

sed -e 's/\s* / /g;s/&/ ~& /g' | column -s '~' -t

However, it may fail under certain circumstances (e.g. when using \&), but it is small and beautiful 😉

Written by Thomas Fischer

May 12, 2008 at 0:00

Posted in LaTeX, Linux