Northward Midget Pole to Pole


Shell Nuggets: Quickie Tabulizer

I'm real bad about things lining up.  Used to go out of my way to ensure variable declarations were columnized by access mode, type, name, equals sign and initial value.

final BufferedImage mapImg = MapImageFactory.newInstance(width, height);
final int           count  = ad.getPosition() * 2;

mapImg.composite(adImg, 25               , (this.adHeight + 20) * count + 20, Over);
mapImg.composite(adTxt, 25 + this.adWidth, (this.adHeight + 20) * count + 20, Over);

The Tabularizer plugin for vim was a boon for productivity.  Well, mine.  For everyone else, it meant either destroying the pre-formatted beauty or re-aligning all the columns.

Anyway, it's considered bad practice, so I've tried to get away from it-- at least when writing shared code.  I still like perfect tabular output in my day-to-day.  Take the df command, for example.  It's default "human readable sizes" output:

2016-02-05 11:03:57 «««« ~
 rons@rons-VM$ df -h
Filesystem            Size  Used Avail Use% Mounted on
                       59G   29G   27G  52% /
/dev/sda1              99M   33M   61M  36% /boot
tmpfs                 1.5G     0  1.5G   0% /dev/shm

Bleah. A line break. Why you mess my rows, GNU? An easy fix jumped into my noggin the other day and crept down my arms and out my fingertips:

2016-02-05 11:03:58 «««« ~
 rons@rons-VM$ df -h | sed 's/Mounted on$/Mount/;' | xargs printf '%-40.40s %8s %8s %8s %5s  %s\n'
Filesystem                                   Size     Used    Avail  Use%  Mount
/dev/mapper/VolGroup00-LogVol00               59G      29G      27G   52%  /
/dev/sda1                                     99M      33M      61M   36%  /boot
tmpfs                                        1.5G        0     1.5G    0%  /dev/shm

The trick is that a printf format with a trailing newline will repeat if it runs out of input tokens.   That's why I had to truncate the "Mounted on" to just "Mount" above-- otherwise there would be an irregular number of columns (and thus printf tokens) on each line/row.  Spaces in filesystems and mounts will mess it up, too, but if you use spaces in the names of your mounts, you deserve the dissonance.

Edit: Better shell function replacement below.

unset -f df ; function df() {
  command df -P $@ | perl -ane '
    push(@rows, [@F]);
    for (0..$#F) {
      $ll = length($F[$_]); $cm[$_] = $ll if $ll > ($cm[$_] // 0);
    END { printf("%-$cm[0]s %$cm[1]s %$cm[2]s %$cm[3]s %$cm[4]s %s\n", @{$_})
      for @rows; }';
} ;


Uses the -P flag for POSIX one-line-per-mount format.   Dynamically calculates column widths.


Posted by Quinn

Tagged as: , Leave a comment
Comments (0) Trackbacks (0)

No comments yet.

Leave a comment

No trackbacks yet.