Unix: Recursive search for text in files

Keep forgetting how to do this, so here it is. How to do a quick and simple, recursive search for text using grep. Hint: It’s very simple.

$ grep -rl "some text" .

That’s all there is to it! grep is the command, r makes the search recursive (i.e. in the target folder and all its sub-folders), l means it will list the name of all the files where it finds the text, "some text" is the string to search for, and finally, the dot at the end means to start the search in the current directory. And just to clarify, this searches for text inside of files, in the content of the files; not the filenames.

There, now I know where to find it when I forget it next time. And perhaps I have helped someone else too :)

Good night!

  • http://tehk.org triune

    sure did (help someone)… replacing this (my old search script)

    grep $1 $(find . -type f)

    with yours… its faster and more accurate!

    THANKS!

    • http://www.geekality.net Torleif

      Yeah, I had something like that before too :D Good to hear someone else found it helpful!

  • Hans

    Thanks!

  • sunil

    Didn’t Worked for me. Any thoughts?

    $ grep -rl 20680483 .

    grep: illegal option — r
    Usage: grep -hblcnsviw pattern file . . .

    • Louis

      sunil: Afraid that the “-r” argument only works for Linux, conventional Unix is a little behind the times here. ;) As an alternative you could try this:

      find . -exec grep -i open_vac {} /dev/null \;

      Here “find” (which is recursive) passes files to “grep” and does the same thing as “-r”.

      • Herman Muller

        You could also add the -l to the grep to just list the files if that is what you want.

    • Louis

      Whoops, in my example for an alternative to “-r”, “open_vac” is the search term and was cut-and-pasted from code I was using. Of course, put whatever text you need there.

  • G

    Nice ! worked well. Thanks.

  • Lo Lee

    this is the simplest way of doing it that i’ve found on the web and it works great. nice!