POSIX – Equivalent to column -t Command

posixtext formatting

I was recently surprised to find out, that the POSIX
list
of utilities doesn't include the
column
utility. column first appeared way back in 4.3BSD, and
it's is pretty useful. Is there a POSIX equivalent of it?


The exact command I would like to replace is:

$ more -- ./tmp.txt 
1   SMALL   000a
2   VERY_VERY_VERY_VERY_LONG    000b
3   SMALL   000c
$ column -t -- ./tmp.txt 
1  SMALL                     000a
2  VERY_VERY_VERY_VERY_LONG  000b
3  SMALL                     000c
$

That is, expand tabs to create prettier columns.

Best Answer

POSIX prefers to codify existing behavior, and to only mandate new features or features that are not widely adopted when the existing behavior is unsatisfactory. Nowadays there isn't much call for presentation of data using unformatted text in fixed-width fonts, so column is unlikely to become mandatory. Unlike pr, it's from BSD, it isn't present System V and other historical unices, so it isn't grandfathered in.

Like any other text utility, you can express it in awk with a moderate amount of work. Here's a minimally tested implementation of column -t. Awk's -v option is similar to column's -s in simple cases (with a single character).

#!/usr/bin/env awk
{
    if (max_column < NF) max_column = NF;
    for (i = 1; i <= NF; i++) {
        if (width[i] < length($i)) width[i] = length($i);
        data[NR, i] = $i;
    }
}
END {
    for (i = 1; i < max_column; i++) format[i] = sprintf("%%-%ds  ", width[i]);
    format[max_column] = "%s\n";
    for (k = 1; k <= NR; k++) {
        for (i = 1; i <= max_column; i++) printf format[i], data[k, i];
    }
}