Ubuntu – align columns right

bashcommand linetext;

For the command shell, is there a common program like column that has an option to align specific or all columns to the right, if not also detect numeric fields and do so automatically for those?

Otherwise what might be the most concise way with text-processing commands?

Example space-delimited input already piped through | column -t:

TVN         20120419  10.08  10.08  9.15   9.6    1630000  9.17    20120419  4.6      83.88   7376600    -0.21858
INTEGERPL   20120419  143.1  148.9  140.3  142.5  2910     138.53  20120405  4.32503  5.55    1642500    1.26158
JSW         20120419  93.55  94.4   91.25  92.7   116000   90.07   20120329  3.86997  8.54    13155770   1.29315
KERNEL      20120419  73.7   74.9   72.9   74.1   56200    71.8    20120404  3.48432  10.71   2819790    1.50892
EUROCASH    20120419  39.49  41.99  39.01  40.73  812000   38.05   20120328  4.85095  20.21   5280548    2.46091
PEKAO       20120419  145.9  147.8  144.0  145.5  292000   140.2   20120404  3.70615  5.48    68858748   2.63889
PKNORLEN    20120419  38.0   38.5   37.25  37.35  1230000  36.26   20120329  4.15476  21.21   104607200  2.65772

Notice readability issues esp. where differences between records are by several magnitudes (like 2nd last column).
Incidentally, formatting prices to always show N decimal places is a problem of its own. But I've used awk's OFMT="%.4f" for that.

Best Answer

Alignment and numeric field detection can be achieved by the following simple awk program.

{
    width=10;
    separator="|";

    for (i=1; i<=NF; i++) {
        if (match($i, /[-+]*[0-9]+[\.]*[0-9]*/)) {
            printf("%"width"s", $i);
        }
        else { 
            printf("%-"width"s", $i);
        }
        if (i == NF) printf("\n");
        else printf("%s", separator);
    }
}

Save it as column.awk.

To test how it works try the following:

echo "abc -1.2 def 2 3 hij" | awk -f column.awk

The output is:

abc       |      -1.2|def       |         2|         3|hij

There are 2 tunable parameters inside the .awk script:

  • width: the default field with (used for alignment)
  • separator: used to separate output columns
Related Question