grep, but only certain file extensions

Jasmine picture Jasmine · Sep 20, 2012 · Viewed 690.5k times · Source

I am working on writing some scripts to grep certain directories, but these directories contain all sorts of file types.

I want to grep just .h and .cpp for now, but maybe a few others in the future.

So far I have:

{ 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]

Can anyone show me how I would add just the specific file extensions?

Answer

Nelson picture Nelson · Sep 20, 2012

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.