title: Bash: Counting instances of a string in text file with a loop
body: <p>I am trying to write a simple bash script in which it takes in a text file, loops through the file and tells me how many times a certain string appears in the file. I want to eventually use this for a custom log searcher (for instance, search for the words 'log in' in a particular log file, etc.), but am having some difficulty as I am relatively new to bash. I want to be able to quickly search different logs for different terms at my will and see how many times they occur. Everything works perfectly until I get down to my loops. I think that I am using grep wrong, but am unsure if that is the issue. My loop codes may seem a little strange because I have been at it for a while and have been constantly tweaking things. I have done a bunch of searching but I feel like I am the only one who has ever had this issue (hopefully not because it is incredibly simple and I just suck). Any and all help is greatly appreciated, thanks in advance everyone.</p>
  
  <p>edit: I would like to account for every instance of the string and not just
  one instance per line</p>
  
  <pre><code>#!/bin/bash
  
  echo "This bash script counts the instances of a user-defined string in a file."
  
  echo "Enter a file to search:"
  
  read fileName
  
  echo " "
  
  echo $path
  
  if [ -f "$fileName" ] || [ -d "$fileName" ]; then
  
  echo "File Checker Complete: '$fileName' is a file."
  echo " "
  echo "Enter a string that you would like to count the occurances of in '$fileName'."
  
  read stringChoice
  echo " "
  echo "You are looking for '$stringChoice'. Counting...."
  
  #TRYING WITH A WHILE LOOP
  count=0
  cat $fileName | while read line
  do
      if echo $line | grep $stringChoice; then
          count=$[ count + 1 ]
  done
  echo "Finished processing file"
  
  
  
  
  #TRYING WITH A FOR LOOP
  #    count=0
  #    for i in $(cat $fileName); do
  #        echo $i  
  #        if grep "$stringChoice"; then
  #            count=$[ $count + 1 ]
  #            echo $count
  #        fi
  #    done
  
  if [ $count == 1 ] ; then
      echo " "
      echo "The string '$stringChoice' occurs $count time in '$fileName'."
  
  elif [ $count &gt; 1 ]; then
      echo " "
      echo "The string '$stringChoice' occurs $count times in '$fileName'."
  
  fi
  elif [ ! -f "$fileName" ]; then
  
  echo "File does not exist, please enter the correct file name."
  
  fi
  </code></pre>