Alexander Cska
Alexander Cska

Reputation: 818

Repeating the format specifiers in awk

I am trying to format the output of the AWK's printf() function. More precisely, I am trying to print a matrix with very long rows and I would like to wrap them and continue on the next line. What I am trying to do is best illustrated using Fortran. Consider the following Fortran statement:

 write(*,'(10I5)')(i,i=1,100)

The output would be the integers in the range 1:100 printed in rows of 10 elements.

Is it possible to do the same in AWK. I could do that by offsetting the index and printing to new line with "\n". The question is whether that can be done in an elegant manner as in Fortran.

Thanks,

As suggested in the comments I would like to explain my Fortran code, given as an example above.

     (i,i=1,100) ! => is a do loop going from 1 to 100
     write(*,'(10I5)') ! => is a formatted write statement 
     10I5 says print 10 integers and for each integer allocate 5 character slot

The trick is, that when one exceeds the 10 x 5 character slots given by the formatted write, one jumps on the next line. So one doesn't need the trailing "\n".

Upvotes: 2

Views: 607

Answers (1)

Akshay Hegde
Akshay Hegde

Reputation: 16997

This may help you

[akshay@localhost tmp]$ cat test.for

    implicit none
    integer i
    write(*,'(10I5)')(i,i=1,100)
    end

[akshay@localhost tmp]$ gfortran test.for

[akshay@localhost tmp]$ ./a.out 
    1    2    3    4    5    6    7    8    9   10
   11   12   13   14   15   16   17   18   19   20
   21   22   23   24   25   26   27   28   29   30
   31   32   33   34   35   36   37   38   39   40
   41   42   43   44   45   46   47   48   49   50
   51   52   53   54   55   56   57   58   59   60
   61   62   63   64   65   66   67   68   69   70
   71   72   73   74   75   76   77   78   79   80
   81   82   83   84   85   86   87   88   89   90
   91   92   93   94   95   96   97   98   99  100

[akshay@localhost tmp]$ awk 'BEGIN{for(i=1;i<=100;i++)printf("%5d%s",i,i%10?"":"\n")}'
    1    2    3    4    5    6    7    8    9   10
   11   12   13   14   15   16   17   18   19   20
   21   22   23   24   25   26   27   28   29   30
   31   32   33   34   35   36   37   38   39   40
   41   42   43   44   45   46   47   48   49   50
   51   52   53   54   55   56   57   58   59   60
   61   62   63   64   65   66   67   68   69   70
   71   72   73   74   75   76   77   78   79   80
   81   82   83   84   85   86   87   88   89   90
   91   92   93   94   95   96   97   98   99  100

Upvotes: 2

Related Questions