title: Problems with my shell script... (grep)
body: <p>I'm sorry to be posting about another problem with the same script that I was working on yesterday.</p>
  
  <p>Originally I had a problem with it <code>cd</code>ing to paths with spaces, though that is fixed now. The problem is that if a 3rd argument is given to the script, it is to search for it within the files it found earlier and then print the files location as well as the line number the term was found on.</p>
  
  <p>For some reason <code>grep</code> isn't liking paths to files that contain spaces (again right? -.-) even though I have double quoted the variable I am <code>grep</code>ing.</p>
  
  <p>Does anyone have any ideas about how to fix it?</p>
  
  <pre><code>#!/bin/bash
  
  path = $1 #1st arg is the path to be searched
  regex = $2 #2nd arg is a regular expression
  searchTerm = $3 #3rd arg is an optional search term
  startDir = `pwd` #Stores the starting path
  getDirs()
  { #Function to get the directories
      for i in "$1"
      ; do
          if [ -d "$i" ]; then
              echo "$i" &gt;&gt; temp.txt
              getDirs "$i"
          fi
      done
  }
  
  getFiles() {        # Function to get files matching the regex
  
      while IFS= read -r path; do # While there is a line, read it, backslash is not a delimiter
          cd "$path"
  
          temp=`ls -1 | grep "$regex"`    #List the contents of the dir. Store only files that match the regex
  
          for j in $temp
          do
              echo "$path/$j" # For every file stored, print its location
          done
          cd $startDir
      done &lt; temp.txt # Read from temp.txt
  }
  
  searchFiles() { # Function to search within files
  
  
      for a in $output1 # For every file found
      do
          out=`grep -n "$searchTerm" "$a" | cut -d: -f 1` # Find the line numbers in which it is present, stop showing after 1st :
          for i in $out   # For every line found
          do
              echo "$a: line $i"  # Print the file location, and the line numbers of the terms
          done
      done
  }
  
  numArgs=$#
  
  echo "$path" &gt;&gt; temp.txt
  getDirs $path   # Getting directories to search
  
  output1=`getFiles`
  
  cd $startDir
  
  if [ $numArgs == 3 ] # If a search term is specified
  then
      searchFiles # Then search the files for it
  else
      echo "$output1" # Otherwise, just print the location of the files
  fi
  
  rm temp.txt # Removing temporary files
  exit 0
  </code></pre>