Press "Enter" to skip to content

Techy: Recursive Find and Grep

Last updated on August 20, 2007

Here’s another little Linux “script snippet” I’ve needed over the past few days: basically, give it a directory/folder and it’ll search all the files in that directory for a set word, words, phrase (or even a string of characters). Very handy if you can tell that a server obviously knows about the domain, but try as you might – you can’t figure out which site the domain name belongs to (as it’s an add on domain and the dratted Ensim control panel won’t allow you to show it). Quick search on the Apache configuration folder and bingo!

I’m entering it here so a) if anybody else needs it, they can easily find it by searching for things such as “grep”, “recursive”, “search”, “linux”, “files” and “find”, and b) so I don’t have to bother remembering the syntax myself 😉

find [start folder name] -type f -exec grep ‘[text you are searching for]’ {} \; -print

Quick explanation:

  • “find XXX”: search the following folder(s)
  • “-type f”: for file(s)
  • “-exec”: then run the following command:
  • “grep ‘search text’ {} \;” use the grep function to search the file for the text
  • “-print” and then display the file name and details

3 Comments

  1. From the grep manpage:

    -R, -r, –recursive
    Read all files under each directory, recursively;
    this is equivalent to the -d recurse option.

  2. Dan Dan

    grep -r never works for me. Dunno why.

  3. Paulson Peter Paulson Peter

    Yes, somehow -R doesn’t work for grep.
    But to do the same using the find shown above, you don’t require it. Find itself is having a “start folder name”. That is implicitly recursive.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.