stackoverflow
stackoverflow

Reputation: 19434

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?

How do I use grep to search the current directory for any and all files containing the string "hello" and display only .h and .cc files?

Upvotes: 201

Views: 380151

Answers (8)

Abhishake Gupta
Abhishake Gupta

Reputation: 3170

To search in current directory recursively:

grep -r 'myString' .

Upvotes: 35

stackoverflow
stackoverflow

Reputation: 19434

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

Upvotes: 210

user1733951
user1733951

Reputation: 43

The simplest way : grep -Ril "Your text" /

Upvotes: -2

Jack
Jack

Reputation: 1525

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)$'`

Upvotes: 8

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72735

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

Check the manual pages for find and xargs for details.

Upvotes: 21

glenn jackman
glenn jackman

Reputation: 246744

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.

Upvotes: 2

Jonathan Leffler
Jonathan Leffler

Reputation: 753455

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.

Upvotes: 6

Donald Miner
Donald Miner

Reputation: 39883

You can pass in wildcards in instead of specifying file names or using stdin.

grep hello *.h *.cc

Upvotes: 60

Related Questions