If I read your question carefully, you ask to "grep to search the current directory for any and all files containing the string "hello" and display only .h and .cc files". So to meet your precise requirements here is my submission:
This displays the file names:
grep -lR hello * | egrep '(cc|h)$'
...and this display the file names and contents:
grep hello `grep -lR hello * | egrep '(cc|h)$'`
If you need a recursive search, you have a variety of options. You should consider ack
.
Failing that, if you have GNU find
and xargs
:
find . -name '*.cc' -print0 -o -name '*.h' -print0 | xargs -0 grep hello /dev/null
The use of /dev/null
ensures you get file names printed; the -print0
and -0
deals with file names containing spaces (newlines, etc).
If you don't have obstreperous names (with spaces etc), you can use:
find . -name '*.*[ch]' -print | xargs grep hello /dev/null
This might pick up a few names you didn't intend, because the pattern match is fuzzier (but simpler), but otherwise works. And it works with non-GNU versions of find
and xargs
.
The simplest way : grep -Ril "Your text" /
To search in current directory recursively:
grep -r 'myString' .
grep -l hello **/*.{h,cc}
You might want to shopt -s nullglob
to avoid error messages if there are no .h or no .cc files.
You can pass in wildcards in instead of specifying file names or using stdin.
grep hello *.h *.cc
find . -name \*.cc -print0 -or -name \*.h -print0 | xargs -0 grep "hello"
.
Check the manual pages for find
and xargs
for details.
Source: Stackoverflow.com