grep, but only certain file extensions

2019-01-12 13:15发布

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?

11条回答
你好瞎i
2楼-- · 2019-01-12 13:49

How about:

find . -name '*.h' -o -name '*.cpp' -exec grep "CP_Image" {} \; -print
查看更多
狗以群分
3楼-- · 2019-01-12 13:49

There is no -r option on HP and Sun servers, this way worked for me on my HP server

find . -name "*.c" | xargs grep -i "my great text"

-i is for case insensitive search of string

查看更多
手持菜刀,她持情操
4楼-- · 2019-01-12 13:49

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.

查看更多
闹够了就滚
5楼-- · 2019-01-12 13:56

Just use the --include parameter, like this:

grep -r -i --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP email@domain.com

that should do what you want.

Syntax notes:

  • -r - search recursively
  • -i - case-insensitive search
  • --include=\*.${file_extension} - search files that match the extension(s) or file pattern only
查看更多
欢心
6楼-- · 2019-01-12 13:56

The easiest way is

find . -type  f -name '*.extension' | xargs grep -i string 
查看更多
登录 后发表回答