title: How do I limit a grep command in UNIX to a specific file and a specific directory in shell script
body: <p>I'm trying to use the grep command to find a unique string in each line of a file containing thousands of lines in a specific directory and save the output in a single line in a new file(e.g. output.txt). I then repeat the process for many more files storing all output in the same file.</p>
  <p>However, the output for each line using the grep command far exceeds the total number of lines in each file, and the output also contains results for only one file instead of many more hundreds. Furthermore, in order not to alter any of the files in the directory, I copied the directory to another location in order to protect the original. Below is the code (with comments) I wrote for your viewing and help;</p>
  <pre><code>#!/bin/bash
  IFS=$'\n' read -d '' -r -a genomes &lt; list.txt
  j=0
  m=0
  grep -o Eco.* ./${genomes[j]}_ani_output.txt | cut -c 59- | cut -d '/' -f 1 &gt;&gt; list1
  IFS=$'\n' read -d '' -r -a genome_names &lt; list1 
  rm list1
  
  while [ $m -eq 0 ] 
  do
      for((i=0; i&lt;=16547; i++))
      do
          grep -w ${genome_names[i]} ./${genomes[j]}_ani_output.txt &gt;&gt; list2 # grep command to fine unique genome names in a specific order. This grep command in the for loop is the problem. generates wrong outputs
      done
  
      if ((i=16547))
      then      
          cut -f 3 list2 &gt;&gt; list3
          rm list2                    
  
          IFS=$'\n' read -d '' -r -a values &lt; list3 
          echo &quot;${genomes[j]} ${values[*]}&quot; &gt;&gt; table
          i=$((i-i))            
          j=$((j+1))              
          rm list3
          unset name 
      fi
  
      if ((j=1000))
      then
          m=$((m+1))
      fi
  done
  </code></pre>
  <p>The first cut command is used to get the genome name in the second column of the file named list1 as can be seen in the attached image. The second cut is used to get the values of each genome. The number 16547 is the total number of lines found in each file.</p>
  <p><a href="https://i.stack.imgur.com/9unyd.png" rel="nofollow noreferrer">content of file with unique genome names in second column retrieved using first cut command</a></p>