arraysawkprintfformatted

Awk: formatted print of varying number of elements


I want to printf records with varying number of elements, or, for example, a jagged array. The element types are a %s followed by undeterminate number of %d.

Example input, pseudo-code, desired output:

$ echo "abc 1 2 3 4 5
  def 8 9
  sometext 5000 23 4 34 56 112" |
awk '{printf "% 10s % 5d % 5d*.......", <each element>'
$        abc     1     2     3     4     5
         def     8     9
    sometext  5000    23     4    34    56   112

% 5d*....... How to specify a repeating format sub-string?

<each element> How to declare each element?

Is there an (g)awk equivalent to C's vprintf or say printf "%s *%d" el for el in array where the %d specifier is automatically repeated the correct number of times.

I can't find anything on google which I find surprising. I can't imagine I'm the first person to want to print jagged arrays in a pretty formatted way.


Solution

  • echo "abc 1 2 3 4 5
      def 8 9
      sometext 5000 23 4 34 56 112" | 
    awk '{printf "%10s", $1 OFS; 
          for(i=2;i<=NF;i++) printf "%5d", $i OFS;
          print ""}'
    
    
    
          abc     1    2    3    4    5
          def     8    9
     sometext  5000   23    4   34   56  112