简体   繁体   中英

How do I use grep to search the current directory for all files having the a string “hello” yet display only .h and .cc files?

如何使用grep在当前目录中搜索包含字符串“hello”的任何和所有文件,并仅显示.h和.cc文件?

grep -r --include=*.{cc,h} "hello" .

This reads: search recursively (in all sub directories also) for all .cc OR .h files that contain "hello" at this . (current) directory

From another stackoverflow question

您可以传入通配符,而不是指定文件名或使用stdin。

grep hello *.h *.cc

find . -name \\*.cc -print0 -or -name \\*.h -print0 | xargs -0 grep "hello" find . -name \\*.cc -print0 -or -name \\*.h -print0 | xargs -0 grep "hello" .

Check the manual pages for find and xargs for details.

要以递归方式在当前目录中搜索:

grep -r 'myString' .

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 .

grep -l hello **/*.{h,cc}

如果没有.h或没有.cc文件,您可能想购买shopt -s nullglob以避免错误消息。

最简单的方法:grep -Ril“你的文字”/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM