Computer Reference: Unix



  • Category
    Unix
  • Title
    Find files in a path which contain a search string (grepfor)
  • Description

    Many Unix commands provide extreme flexibility but may sometimes be obtuse enough that learning to use that flexibility requires patience, experimentation, or, especially a friend or associate who has a bit of expertise.

    Thanks to Mark Childs for this hint. It allows the user to find all instances of a string in all of the files in a specified directory, and its subdirectories

      • First off, you need to create a shell script with the following contents
    • with the filename grepfor
    • and contents:

    if ( grep "$1" "$2" );
    then echo "====== $2"
    fi

      • Now make the file executable by executing the following Unix command:

    chmod a+x grepfor

      • Now move the file into a directory which is in your Unix execution PATH.  If you don't have such, see the Unix tip on Creating a directory in your execution PATH.
         
      • To use grepfor, enter the command with the following syntaxThe syntax is wierd, but all you really need to do is enter the following into the Unix Command line, substituting with the pathname of the directory you wish to search, and replacing  with the text which you are attempting to find.

        find [path] -type f -exec grepfor [searchString] {} \;