Jas*_*son 880 unix linux search command-line grep
我正在编写一些脚本到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@domain.com
Run Code Online (Sandbox Code Playgroud)
任何人都可以告诉我如何添加特定的文件扩展名?
Nel*_*son 1228
只需使用--include参数,如下所示:
grep -r -i --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP email@domain.com
Run Code Online (Sandbox Code Playgroud)
应该做你想要的.
语法说明:
-r - 递归搜索-i- 不区分大小写的搜索--include=\*.${file_extension} - 仅搜索与扩展名或文件模式匹配的文件Hol*_*ger 261
其中一些答案似乎语法太重,或者它们在我的Debian服务器上产生了问题.这对我很有用:
PHP革命:如何在Linux中Grep文件,但只有某些文件扩展名?
即:
grep -r --include=\*.txt 'searchterm' ./
Run Code Online (Sandbox Code Playgroud)
...或不区分大小写的版本......
grep -r -i --include=\*.txt 'searchterm' ./
Run Code Online (Sandbox Code Playgroud)
grep:命令
-r:递归
-i:ignore-case
--include:all*.txt:文本文件(用\文件转义,以防万一你的文件名中有一个带星号的目录)
'searchterm':搜索什么
./:从当前目录开始.
Yur*_*lov 50
grep -rnw "some thing to grep" --include=*.{module,inc,php,js,css,html,htm} ./
Run Code Online (Sandbox Code Playgroud)
Ami*_*ani 48
怎么样:
find . -name '*.h' -o -name '*.cpp' -exec grep "CP_Image" {} \; -print
Run Code Online (Sandbox Code Playgroud)
Sam*_*m B 16
HP和Sun服务器上没有-r选项,这种方式适用于我的HP服务器
find . -name "*.c" | xargs grep -i "my great text"
Run Code Online (Sandbox Code Playgroud)
-i用于不区分大小写的字符串搜索
fed*_*qui 12
由于这是查找文件的问题,让我们使用find!
使用GNU find,您可以使用该-regex选项在扩展名为.h或的目录树中查找这些文件.cpp:
find -type f -regex ".*\.\(h\|cpp\)"
# ^^^^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
然后,只需执行grep每个结果:
find -type f -regex ".*\.\(h\|cpp\)" -exec grep "your pattern" {} +
Run Code Online (Sandbox Code Playgroud)
如果你没有这种发现的分布,你必须使用类似Amir Afghani的方法,使用-o连接选项(名称以.h或以结尾.cpp):
find -type f \( -name '*.h' -o -name '*.cpp' \) -exec grep "your pattern" {} +
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
如果您真的想使用grep,请按照指示的语法--include:
grep "your pattern" -r --include=*.{cpp,h}
# ^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
小智 7
最简单的方法是
find . -type f -name '*.extension' | xargs grep -i string
Run Code Online (Sandbox Code Playgroud)
ag(银色搜索器)的语法非常简单
-G --file-search-regex PATTERN
Only search files whose names match PATTERN.
Run Code Online (Sandbox Code Playgroud)
所以
ag -G *.h -G *.cpp CP_Image <path>
Run Code Online (Sandbox Code Playgroud)
这个答案很好:
grep -r -i --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP email@domain.com
Run Code Online (Sandbox Code Playgroud)
但它可以更新为:
grep -r -i --include \*.{h,cpp} CP_Image ~/path[12345] | mailx -s GREP email@domain.com
Run Code Online (Sandbox Code Playgroud)
哪个可以更简单。