title: BASH - Summarising information from several fields in unique field using Loop and If statements
body: <p>I have the following tab-separated file:</p>
  
  <pre><code>A1      A1      0       0       2       1       1 1     1 1     1 1     2 1     1 1
  A2      A2      0       0       2       1       1 1     1 1     1 1     1 1     1 1
  A3      A3      0       0       2       2       1 1     2 2     1 1     1 1     1 1
  A5      A5      0       0       2       2       1 1     1 1     1 1     1 2     1 1
  </code></pre>
  
  <p>The idea is to summarise the information between column 7 (included) and the end in a new column that is added at the end of the file.</p>
  
  <p>To do so, these are the rules:</p>
  
  <ul>
  <li><p>If the total number of “2”s in the row (between column 7 and the end) is <strong>0</strong>: add “1 1” to the new last column</p></li>
  <li><p>If the total number of “2”s in the row (between column 7 and the end) is <strong>1</strong>: add “1 2” to the new last column</p></li>
  <li><p>If the total number of “2”s in the row (between column 7 and the end) is <strong>2 or more</strong>: add “2 2” to the new last column</p></li>
  </ul>
  
  <p>I started to extract the columns I want to work on using the command:</p>
  
  <blockquote>
    <p>awk '{for (i = 7; i &lt;= NF; i++) printf $i " "; print ""}' myfile.ped > tmp_myfile.txt</p>
  </blockquote>
  
  <p>Then I count the number of occurrence in each row using:</p>
  
  <blockquote>
    <p>sed 's/[^2]//g' tmp_myfile.txtt | awk '{print NR, length }' >
    tmp_occurences.txt</p>
  </blockquote>
  
  <p>Which outputs:</p>
  
  <pre><code>1 1
  2 0
  3 2
  4 1
  </code></pre>
  
  <p>Then my idea was to write a for loop that loops through the lines to add the new summary column. 
  I was thinking in this kind of <em>structure</em>, based on what I found here: <a href="http://www.thegeekstuff.com/2010/06/bash-if-statement-examples" rel="nofollow">http://www.thegeekstuff.com/2010/06/bash-if-statement-examples</a>:</p>
  
  <pre><code>while read line ;
  do
      set $line
  
      If ["$2"==0]
      then
          $3=="1 1"
  
      elif ["$2"==1 ]
      then
          $3=="1 2”
  
      elif ["$2"&gt;=2 ]
      then 
          $3==“2 2”
  
      else
          print ["error"]
  
      fi
  done &lt; tmp_occurences.txt
  </code></pre>
  
  <p>But I am stuck here. Do I have to create the new column before starting the loop? Am I going in the right direction? </p>
  
  <p>Ideally, the final output (after merging the first 6 columns from the initial file and the summary column) would be:</p>
  
  <pre><code>A1      A1      0       0       2       1       1 2
  A2      A2      0       0       2       1       1 1
  A3      A3      0       0       2       2       2 2
  A5      A5      0       0       2       2       1 2 
  </code></pre>
  
  <p>Thank you for your help!</p>