How can I grep recursively, but only in files with certain extensions? – Dev

The best answers to the question “How can I grep recursively, but only in files with certain extensions?” in the category Dev.

QUESTION:

I’m working on a script to grep certain directories:

{ grep -r -i CP_Image ~/path1/;
grep -r -i CP_Image ~/path2/;
grep -r -i CP_Image ~/path3/;
grep -r -i CP_Image ~/path4/;
grep -r -i CP_Image ~/path5/; }
| mailx -s GREP [email protected]

How can I limit results only to extensions .h and .cpp?

ANSWER:

Some of these answers seemed too syntax-heavy, or they produced issues on my Debian Server. This worked perfectly for me:

grep -r --include=\*.txt 'searchterm' ./

…or case-insensitive version…

grep -r -i --include=\*.txt 'searchterm' ./
  • grep: command

  • -r: recursively

  • -i: ignore-case

  • --include: all *.txt: text files (escape with \ just in case you have a directory with asterisks in the filenames)

  • 'searchterm': What to search

  • ./: Start at current directory.

Source: PHP Revolution: How to Grep files in Linux, but only certain file extensions?

ANSWER:

Just use the --include parameter, like this:

grep -inr --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP [email protected]

That should do what you want.

To take the explanation from HoldOffHunger’s answer below:

  • grep: command

  • -r: recursively

  • -i: ignore-case

  • -n: each output line is preceded by its relative line number in the file

  • --include \*.cpp: all *.cpp: C++ files (escape with \ just in case you have a directory with asterisks in the filenames)

  • ./: Start at current directory.

ANSWER:

Use:

find . -name '*.h' -o -name '*.cpp' -exec grep "CP_Image" {} \; -print

ANSWER:

grep -rnw "some thing to grep" --include=*.{module,inc,php,js,css,html,htm} ./