title: Bash loop producing unwanted duplicate results
body: <p>I am working in bash.  I am trying to find unique barcodes within strings in a .txt file.  Each string can contain 3 barcodes.  I want to identify and label each unique configuration that contains my barcodes of interest. </p>
  
  <p>This is my starting <code>reads.txt</code> file that contains the strings I want to evaluate.</p>
  
  <pre><code>ABCD1
  EFGH2
  ABGH1
  EFCD2
  </code></pre>
  
  <p>As an example the barcodes contained in <code>ABCD1</code> are <code>AB</code>, <code>CD</code> and <code>1</code>.</p>
  
  <p>My desired result is to identify only srings <code>ABCD1</code> and <code>EFGH2</code> and to store each of them respectively as <code>result.1.txt</code> and <code>result.2.txt</code> </p>
  
  <p>Bellow is my attempt.</p>
  
  <pre><code># Add the barcode sequences to a bash array
  declare -a BARCODES1=(AB EF)
  declare -a BARCODES2=(CD GH)
  declare -a BARCODES3=(1 2)
  
  # Initialize counter
  count=1
  
  # Search for the barcode sequences in the reads.txt file
  rm ROUND*
  rm result*
  
  for barcode in "${BARCODES1[@]}";
      do
      grep "$barcode1" reads.txt &gt; ROUND1_MATCHES.txt
  
          for barcode2 in "${BARCODES2[@]}";
          do
          grep "$barcode2" ROUND1_MATCHES.txt &gt; ROUND2_MATCHES.txt
  
             for barcode3 in "${BARCODES3[@]}";
              do
              grep "$barcode3" ROUND2_MATCHES.txt &gt; ROUND3_MATCHES.txt
  
                  if [ -s ROUND3_MATCHES.txt ]
                  then
                  mv ROUND3_MATCHES.txt result.$count.txt
                  fi
  
              count=`expr $count + 1`
              done
          done
      done
  </code></pre>
  
  <p>Strangely this code outputs too many results files. Running <code>head results*</code> gives me the following.</p>
  
  <pre><code>==&gt; result.1.txt &lt;==
  ABCD1
  
  ==&gt; result.2.txt &lt;==
  EFCD2
  
  ==&gt; result.3.txt &lt;==
  ABGH1
  
  ==&gt; result.4.txt &lt;==
  EFGH2
  
  ==&gt; result.5.txt &lt;==
  ABCD1
  
  ==&gt; result.6.txt &lt;==
  EFCD2
  
  ==&gt; result.7.txt &lt;==
  ABGH1
  
  ==&gt; result.8.txt &lt;==
  EFGH2
  </code></pre>
  
  <p>The desired result would have been </p>
  
  <pre><code>==&gt; result.1.txt &lt;==
  ABCD1
  
  ==&gt; result.2.txt &lt;==
  EFCD2
  </code></pre>