I am working on writing some scripts to grep
certain directories, but these directories contain all sorts of file types.
I want to grep
jus
ag
(the silver searcher) has pretty simple syntax for this
-G --file-search-regex PATTERN
Only search files whose names match PATTERN.
so
ag -G *.h -G *.cpp CP_Image <path>
Should write "-exec grep " for each "-o -name "
find . -name '*.h' -exec grep -Hn "CP_Image" {} \; -o -name '*.cpp' -exec grep -Hn "CP_Image" {} \;
Or group them by ( )
find . \( -name '*.h' -o -name '*.cpp' \) -exec grep -Hn "CP_Image" {} \;
option '-Hn' show the file name and line.
Just use the --include
parameter, like this:
grep -inr --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP email@domain.com
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.
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?
How about:
find . -name '*.h' -o -name '*.cpp' -exec grep "CP_Image" {} \; -print
The easiest way is
find . -type f -name '*.extension' | xargs grep -i string