Results 1 to 4 of 4
  1. #1
    Join Date
    Feb 2004
    Posts
    52

    Red face Unanswered: Working with columns II

    Hi.

    Yet another problem with columns. Could someone
    shed some light, please ?

    Given a NxM matrix composed by numbers

    2 5 3 ... 4
    1 1 1 ... 3
    0 1 0 ... 2
    ... ...
    3 6 2 ... 9

    I need an awk command to add the numbers in
    each column between the lines A and B (A and B are also inputs).
    Something like

    awk -v <A> <B> -f <script> <matrix.data> <output>

    For example, using the matrix above,

    awk -v 1 3 -f <script> matrix.data would result :

    3 7 4 ... 9

    awk -v 3 3 -f <script> matrix.data would result :

    0 1 0 ... 2

    Thanks for any suggestion !

  2. #2
    Join Date
    Apr 2004
    Location
    Boston, MA
    Posts
    325
    nawk -v cs=1 -v ce=3 -f serg.awk file.txt

    Code:
    BEGIN {
      if ( cs > ce ) {
         printf("ERROR: %d must be > %d\n", ce, cs);
         exit 1;
      }
    
    }
    
    FNR >= cs && FNR <= ce {
      for(i=1; i <= NF; i++)
        arr[i] += $i;
      nf=NF;
    }
    
    END {
      for(i=1; i<=nf; i++)
        printf("%d%s", arr[i], (i == nf) ? "\n" : OFS);
    }

  3. #3
    Join Date
    Jun 2002
    Location
    UK
    Posts
    525
    I'd do this pretty much the same way. Only difference, I'd 'exit' after the last row to be summed was reached (for performance, to avoid reading the rest of the file).

    I'd also create the awk script as an executable, to remove the need for the shell to delegate to awk (i.e. include the header #!/usr/bin/awk -f)

    Code:
    #!/usr/bin/awk -f
    BEGIN {
               if (! startRow || ! endRow) 
               {
                 exitMessage="You must supply startRow and endRow values."; exit
               }
             }
    NR>endRow {exit}
    NR>=startrow {
                   for (i=1;i<=NF;i++)
                   {
                     totals[i]+=$i
                   }
                 }
    END {
          for (j=1;j<=i;j++)
          {
            printf "%s ",totals[j]
          }
          printf exitMessage"\n"
        }
    You would need to give execution permissions on the script...

    chmod 755 sumcols

    And you would call it using...

    sumcols -v startRow=1 -v endRow=3 yourInputFile
    Last edited by Damian Ibbotson; 06-17-04 at 10:53. Reason: A couple of dumb syntax errors

  4. #4
    Join Date
    Feb 2004
    Posts
    52
    Thanks again, Vlad and Damian !

    I am learning a lot with your scripts !!!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •