title: Sum variable in awk 'if condition' under 'for loop'
body: <p>I have a file with 3 columns (n=3) and FS = " " (file1.txt):</p>
  
  <pre><code>cat file1.txt
  3.1 6.6 0
  2.4 7.1 4.9
  5.7 1.2 6.1
  </code></pre>
  
  <p>Here, I would like to give an 'if condition' in <code>awk</code> for each column, where it would test for a condition and return a value of 1 or 0 (depending on the result) and store it in another variable, such as:</p>
  
  <pre><code>#!/bin/bash
  
  #code1
  awk '{
  
  if  ($1 != 0)
  
      { x1 = 1 }
      else
      { x1 = 0}
  
  
  if  ($2 != 0)
  
      { x2 = 1 }
      else
      { x2 = 0}
  
  
  if  ($3 != 0)
  
      { x3 = 1 }
      else
      { x3 = 0}
  
       x = x1 + x2 + x3
       print x;
  
       }' file1.txt &gt; output.txt
  </code></pre>
  
  <p>The desired output in this case would be:</p>
  
  <pre><code>cat output.txt
  2
  3
  3
  </code></pre>
  
  <p>Which I am getting without any problem.</p>
  
  <p>Consider the case in which instead of having 3 columns, there were say 10 columns (n=10) and the same <code>if</code> condition is to be applied to each column. In this case I would like to run a <code>for</code> loop, under which the same <code>if</code> condition is to be defined. But I think I am making an error in specifying the nth field. Also how to perform the sum of the xn variables (x1 + X2 + X3...X10). Here is what I have tried so far:</p>
  
  <pre><code>   awk '{
     for (n=1; n&lt;=10; n++)
  
      if ($n != 0)
  
      { xn = 1 }
  
      else
  
      { xn = 0 }
  
      xn+=xn 
      print xn;
  
               }' file1_10fields.txt &gt; output_10fields.txt
  </code></pre>
  
  <p>This is not giving me the correct output. Where am I making the mistake? Is there a more elegant way to do this?
  Are <code>xn+=xn</code> and <code>print xn</code> supposed to be outside the loop? Also, what is the correct way to get the sum?</p>