我正在编写一些脚本到grep
某些目录,但这些目录包含各种文件类型。
我想grep
现在只是.h
和.cpp
,但未来可能还有其他几个。
到目前为止,我有:
{ 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]
任何人都可以告诉我如何添加特定的文件扩展名?
只需使用--include
参数,如下所示:
grep -r -i --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP [email protected]
应该做你想要的。
语法说明:
-r
- 递归搜索-i
- 不区分大小写的搜索--include=\*.${file_extension}
- 仅搜索与扩展名或文件模式匹配的文件以下答案很好。
grep -r -i --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP [email protected]
但可以更新为:
grep -r -i --include \*.{h,cpp} CP_Image ~/path[12345] | mailx -s GREP [email protected]
哪个可以更简单。
应该为每个“-o -name”写“-exec grep”
find . -name '*.h' -exec grep -Hn "CP_Image" {} \; -o -name '*.cpp' -exec grep -Hn "CP_Image" {} \;
或者按()分组
find . \( -name '*.h' -o -name '*.cpp' \) -exec grep -Hn "CP_Image" {} \;
选项'-Hn'显示文件名和行。
其中一些答案似乎语法太重,或者它们在我的Debian服务器上产生了问题。这对我很有用:
PHP Revolution: How to Grep files in Linux, but only certain file extensions?
即:
grep -r --include=\*.txt 'searchterm' ./
...或不区分大小写的版本......
grep -r -i --include=\*.txt 'searchterm' ./
grep
:命令-r
:递归地-i
:ignore-case--include
:all * .txt:文本文件(用\文件转义,以防你在文件名中有一个带星号的目录)'searchterm'
:搜索什么./
:从当前目录开始。怎么样:
find . -name '*.h' -o -name '*.cpp' -exec grep "CP_Image" {} \; -print
grep -rnw "some thing to grep" --include=*.{module,inc,php,js,css,html,htm} ./
HP和Sun服务器上没有-r选项,这种方式适用于我的HP服务器
find . -name "*.c" | xargs grep -i "my great text"
-i用于不区分大小写的字符串搜索
由于这是找文件的问题,让我们使用find
!
使用GNU find,您可以使用-regex
选项在扩展名为.h
或.cpp
的目录树中查找这些文件:
find -type f -regex ".*\.\(h\|cpp\)"
# ^^^^^^^^^^^^^^^^^^^^^^^
然后,只需在每个结果上执行grep
:
find -type f -regex ".*\.\(h\|cpp\)" -exec grep "your pattern" {} +
如果你没有这个find的分布,你必须使用像Amir Afghani's这样的方法,使用-o
连接选项(名称以.h
或.cpp
结尾):
find -type f \( -name '*.h' -o -name '*.cpp' \) -exec grep "your pattern" {} +
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
如果你真的想使用grep
,请按照--include
指示的语法:
grep "your pattern" -r --include=*.{cpp,h}
# ^^^^^^^^^^^^^^^^^^^
最简单的方法是
find . -type f -name '*.extension' | xargs grep -i string
我知道这个问题有点过时,但我想分享我通常用来查找.c和.h文件的方法:
tree -if | grep \\.[ch]\\b | xargs -n 1 grep -H "#include"
或者如果您还需要行号:
tree -if | grep \\.[ch]\\b | xargs -n 1 grep -nH "#include"
ag
(银色搜索者)有相当简单的语法
-G --file-search-regex PATTERN
Only search files whose names match PATTERN.
所以
ag -G *.h -G *.cpp CP_Image <path>