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
6 Answers
After some trials, I think grep -irn 'string' --include '*.h' is more handy
Set (turn on) the shell option globstar with the command
shopt -s globstarThis will cause ** as a filename component to mean
everything here and below.
So path/** means everything in the path directoryand its subdirectories.
(You don't need to type ./ here.)
Then you can use
grep -in "string" path/**/*.hto search all the .h files in and under path.
You can unset options with shopt -u.
find /path -iname "*.h" -exec grep -inH "string" "{}" \; 2 If you can install something on your machine, I suggest using ack.
You can do exactly what you need with it and much more. For your use case, you can do:
# Depending of your system, you have to use one or the other
ack --hh -i string path
ack-grep --hh -i string path- --hh filters on h files
- -i ignores the case
To find which file filters are supported natively, run the command ack --help=type.
What about this one?
find -L ./path -name "*.h" -exec grep -in "string" {} \;Explanation:
- -L : follow symlinks
- -name : using the asterisk, you can describe extensions
- -in : same as your proposal, but the 'r' is replaced by the
findcommand - {} : this stands for the result of the
findcommand - \; : in case you combine
findwith-exec, this is the end-of-command specifier
If you're using gnu grep then it's got a flag that does exactly what you want:
grep -irn --include=\*.h "string" pathalthough I don't think it's available in other greps.