Grep in files with a specific extension under a directory

Is there a command that allows searching a keyword in files under a directory with specific extension ?

The string grep -irn "string" ./path gives a recursive search for all files under the directory./path. My specific requirement is to search in all files under ./path with an extension such as *.h


Solution 1:

After some trials, I think grep -irn 'string' --include '*.h' is more handy

Solution 2:

Set (turn on) the shell option globstar with the command

    shopt -s globstar

This will cause ** as a filename component to mean everything here and below.  So path/** means everything in the path directory and its subdirectories.  (You don't need to type ./ here.)  Then you can use

grep -in "string" path/**/*.h

to search all the .h files in and under path.


You can unset options with shopt -u.

Solution 3:

find /path -iname "*.h" -exec grep -inH "string" "{}" \;