Black lives matter
Portrait Dr. Axel Rauschmayer
Dr. Axel Rauschmayer
Homepage | Twitter
Cover of book “JavaScript for impatient programmers”
Book, exercises, quizzes
(free to read online)
Cover of book “Deep JavaScript”
Book (50% free online)
Cover of book “Tackling TypeScript”
Book (first part free online)
Logo of newsletter “ news”
Newsletter (free)

Unix shell: search for a text via “find” and “grep”

[2011-10-06] dev, unix, shell
(Ad, please don’t block)

This post shows you how to use “find” and “grep” to search for a text string in all files that are directly or indirectly contained in a given directory.

Example: Find all JavaScript files in the current directory and search for the word “foo”. The easiest way to do this is to execute the command

    grep -iH foo `find . -name "*.js"`
  • Assemble a list of all JavaScript files in the current directory:
        find . -name "*.js"
  • Insert that list after “foo”: backquotes.
  • Go through a list of files, search for the text “foo”:
        grep -i foo <list of files>
    The option i ensure that the search is case-insensitive.
Problems: With many files, the command can become too long and grow beyond the maximum allowed number of characters. Furthermore, the above doesn’t work well with directories whose names have spaces in them. Solution: let “find” call “grep”, as follows.
    find . -name "*.js" -exec grep -iH foo {} \;
  • The command after -exec is invoked for each file name that matches the pattern “*.js”, after the curly braces {} have been replaced with the name. The escaped semicolon “\;” tells -exec where the command ends.
  • The option H tells grep to print the file name when it finds the text (something it doesn’t normally do if it searches a single file).
The above works in bash (t)csh.