Results 1 to 4 of 4

Thread: Using grep recursively with a filename pattern?

  1. #1
    Join Date
    Aug 2009
    Beans
    125

    Using grep recursively with a filename pattern?

    I know how to use grep recursively, grep -r 'hello world' .
    The thing I can't figure out is, how can I search recursively, and make it only check certain files? For example, all .py files.

    I've tried a bunch of things, like grep -r 'string' ./*.py but it didn't work right. Typing grep -r 'string' *.py only seaches the current dir.

  2. #2
    Join Date
    Sep 2009
    Location
    Freiburg/Germany
    Beans
    1,112
    Distro
    Ubuntu 12.10 Quantal Quetzal

    Re: Using grep recursively with a filename pattern?

    The filename patterns are reslved by the shell, grep sees only the filenames they resolve to.

    At least zsh supports the pattern
    Code:
    **/*.py
    for "all .py files in the current dir and its subdirs" (but I don't know about bash).

    Or you can use find:

    Code:
    find . -name \*.py -exec grep foo "{}" + ;
    ClassicMenu Indicator - classic GNOME menu for Unity
    Unsettings - configuration program for the Unity
    Privacy Indicator - easily switch privacy settings in Unity
    Arronax - create and modify app starters

  3. #3
    Join Date
    Jun 2009
    Location
    0000:0400
    Beans
    Hidden!

    Re: Using grep recursively with a filename pattern?

    You're using the proper flag (-r) for searching with grep recursively. You only need to specify *.py for the search term at the end of the command. Are you using double quotes or single quotes? There is a difference, particularly if you're using a pattern.

  4. #4
    Join Date
    Jun 2008
    Location
    California
    Beans
    2,271
    Distro
    Ubuntu 10.10 Maverick Meerkat

    Re: Using grep recursively with a filename pattern?

    I know next to nothing about grep but decided to run some tests and couldn't get things to work as desired by the OP without the find command. I googled a bit and found the following, which does seem to work.

    Code:
    grep -r --include=<pattern> <string> <directory>
    http://www.joeldare.com/wiki/linux:g...file_extension

    The include option is shown in the grep man page as

    --include=GLOB. Search only files whose base name matches GLOB (using wildcard matching as described under --exclude).
    Last edited by kaibob; November 14th, 2009 at 07:59 PM.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •