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@domain.com
Can anyone show me how I would now add just the specific file extensions?
ag
(the silver searcher) has pretty simple syntax for thisso
Since this is a matter of finding files, let's use
find
!Using GNU find you can use the
-regex
option to find those files in the tree of directories whose extension is either.h
or.cpp
:Then, it is just a matter of executing
grep
on each of its results:If you don't have this distribution of find you have to use an approach like Amir Afghani's, using
-o
to concatenate options (the name is either ending with.h
or with.cpp
):And if you really want to use
grep
, follow the syntax indicated to--include
:I am aware this question is a bit dated, but I would like to share the method I normally use to find .c and .h files:
or if you need the line number as well:
Some of these answers seemed too syntax-heavy, or they produced issues on my Debian Server. This worked perfectly for me:
PHP Revolution: How to Grep files in Linux, but only certain file extensions?
Namely:
...or case-insensitive version...
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.Below answer is good.
But can be updated to:
Which can be more simple.