Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

grep

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?

like image 791
Jasmine Avatar asked Sep 20 '12 16:09

Jasmine


People also ask

How do I grep specific files recursively?

To take the explanation from HoldOffHunger's answer below: grep : command. -r : recursively.

How do I grep specific files?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in. The output is the three lines in the file that contain the letters 'not'.

How do I exclude a file type in grep?

Exclude Directories and Files To exclude a directory from the search, use the --exclude-dir option. The path to the excluded directory is relative to the search directory. To exclude multiple directories, enclose the excluded directories in curly brackets and separate them with commas with no spaces.

What command can we use to recursively find all files with an INI extension?

Using Glob() function to find files recursively We can use the function glob.


1 Answers

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.

like image 169
Nelson Avatar answered Sep 23 '22 12:09

Nelson