sta*_*low 151
grep -r --include=*.{cc,h} "hello" .
Run Code Online (Sandbox Code Playgroud)
这将读取:在此.(当前)目录中以递归方式(在所有子目录中)搜索包含"hello"的所有.cc或.h文件
Don*_*ner 47
您可以传入通配符,而不是指定文件名或使用stdin.
grep hello *.h *.cc
Run Code Online (Sandbox Code Playgroud)
Nou*_*him 19
find . -name \*.cc -print0 -or -name \*.h -print0 | xargs -0 grep "hello".
检查手册页find,并xargs了解详细信息.
如果需要递归搜索,则有多种选择。你应该考虑一下ack。
如果您有GNU find和xargs:
find . -name '*.cc' -print0 -o -name '*.h' -print0 | xargs -0 grep hello /dev/null
Run Code Online (Sandbox Code Playgroud)
使用/dev/null确保您可以打印文件名;在-print0和-0涉及包含空格的文件名(换行等)。
如果您没有笨拙的名称(带有空格等),则可以使用:
find . -name '*.*[ch]' -print | xargs grep hello /dev/null
Run Code Online (Sandbox Code Playgroud)
这可能会选择一些您不希望使用的名称,因为模式匹配比较模糊(但更简单),但可以使用。它的工作原理与非GNU版本find和xargs。
如果我仔细阅读你的问题,你要求"grep在当前目录中搜索包含字符串"hello"的任何和所有文件,并仅显示.h和.cc文件".因此,为了满足您的精确要求,我的提交是:
这会显示文件名:
grep -lR hello * | egrep '(cc|h)$'
Run Code Online (Sandbox Code Playgroud)
...这显示文件名和内容:
grep hello `grep -lR hello * | egrep '(cc|h)$'`
Run Code Online (Sandbox Code Playgroud)