Pretty printing LaTeX tables

Miscellaneous

ad free blog

2008-05-12 by Thomas Fischer [en]

Thomas Fischer 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:

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

Keywords: LaTeX, Linux
Trackback-URL: http://www.t-fischer.net/blog/20080512_Pretty_printing_LaTeX_tables

Writing comments is currently not possible. Feel free to write me an email to the address shown on my homepage.

More social bookmarking links than anybody else ;-)
LinkARENAalltagzTechnoratiMister Wongdel.icio.usGoogle BookmarksYiGGsimpyfurlblogmarkstailranktektagoneviewdiggslashdotfolkdyahoo my web
Valid XHTML 1.0!Valid CSS!UTF-8 EncodedUse Metric & SIGentoo LinuxSession Initiation ProtocolAny BrowserWir wollen keine Softwarepatente!Coffee PoweredUnix-AGKDE Developer (KBibTeX)Hacker EmblemPlay OGGXING profileDANTE MemberThe content of this page is licensed under a Creative Commons Attribution-Share Alike 3.0 License, unless noted otherwise.Blog
Date of Modification: 2009-Feb-21 18:08Chuck Norris