[colug-432] Nice Plain Text Columns and Avoiding NIH

Eric Floehr eric at intellovations.com
Mon Aug 8 10:23:23 EDT 2011


I agree with the awk suggestion...

Here is what I would do.  The original program is this:
http://colug.net/~jep/parsegaspriceshtml.awk

Which outputs tab-delimited lines... here is the actual code at the
bottom of the program:

   for (j=0;j<i && True;j++) {
      if (False) {
         print j
         print price[j]
         print name[j]
         print address[j,0]
         print area[j]
         print reporter[j]
         print time[j]
         print timeAgo[j]
      }

      delimiter="\t"
      print price[j] delimiter name[j] delimiter address[j,0]
delimiter area[j] delimiter reporter[j] delimiter time[j] delimiter
timeAgo[j]
   }

What I would do it iterate through once 0 to i and get the length of
the longest string in each array.  Then iterate through again using
printf with the column widths + 1 something like this...

   pricemax = namemax = addressmax = areamax = reportermax = timemax =
timeAgomax = 0
   for (j=0;j<i;j++) {
      if pricemax < length(price[j]) { pricemax = length(price[j]) }
      if namemax < length(name[j]) { namemax = length(name[j]) }
      ...
   }

   formatstring = "%"$pricemax"s %"$namemax"s %"..."\n"
   for (j=0;j<i;j++) {
      printf(formatstring, price[j], name[j], ...)
   }

This is pseudocode, but it seems that this would solve the problem
without too much effort.  I'm not a huge awk programmer so there might
be better ways to get the length of the longest string in an array, or
even a better way to do this.

Now this solves the problem for this particular instance.  If you are
looking for a general way to turn tabs into spaces while ensuring
columns line up correctly (i.e. adding spaces where columns are longer
than the default tab length), I don't have an answer.

Cheers,
Eric



More information about the colug-432 mailing list