The Computer Oracle

How can I "grep" recursively filtering the name of the files I want with wildcards?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Bleepage Open

--

Chapters
00:00 How Can I &Quot;Grep&Quot; Recursively Filtering The Name Of The Files I Want With Wildcards?
00:42 Accepted Answer Score 97
00:52 Answer 2 Score 17
02:17 Thank you

--

Full question
https://superuser.com/questions/757834/h...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#linux #commandline #bash #grep #filefilter

#avk47



ACCEPTED ANSWER

Score 97


Use grep's --include option:

grep -ir "string" --include="*.php" .



ANSWER 2

Score 17


If you have a version of grep that lacks the --include option, you can use the following. These were both tested on a directory structure like this:

$ tree
.
├── a
├── b
│   └── foo2.php
├── c
│   └── d
│       └── e
│           └── f
│               └── g
│                   └── h
│                       └── foo.php
├── foo1.php
└── foo.php

Where all the .php files contain the string string.

  1. Use find

    $ find . -name '*php' -exec grep -H string {} +
    ./b/foo2.php:string
    ./foo1.php:string
    ./c/d/e/f/g/h/foo.php:string
    

    Explanation

    This will find all .php files and then run grep -H string on each of them. With find's -exec option, {} is replaced by each of the files found. The -H tells grep to print the file name as well as the matched line.

  2. Assuming you have a new enough version of bash, use globstar :

    $ shopt -s globstar
    $ grep -H string  **/*php
    b/foo2.php:string
    c/d/e/f/g/h/foo.php:string
    foo1.php:string
    

    Explanation

    As explained in the bash manual:

    globstar

    If set, the pattern ‘**’ used in a filename expansion context will match all files and zero or more directories and subdirectories. If the pattern is followed by a ‘/’, only directories and subdirectories match.

    So, by running shopt -s globstar you are activating the feature and Bash's globstar option which makes **/*php expand to all .php files in the current directory (** matches 0 or more directories, so **/*php matches ./foo.php as well) which are then grepped for string.