我正在编写一些脚本到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
有人能告诉我现在如何添加特定的文件扩展名吗?
答案 0 :(得分:1118)
只需使用--include
参数,如下所示:
grep -r -i --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP email@domain.com
应该做你想做的事。
语法注释:
-r
- 递归搜索-i
- 案例 - 不敏感搜索--include=\*.${file_extension}
- 仅搜索与扩展程序或文件模式匹配的文件答案 1 :(得分:238)
这些答案中的一些似乎过于语法沉重,或者它们在我的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
:command
-r
:递归地
-i
:ignore-case
--include
:所有* .txt:文本文件(以\来转义,以防你的文件名中有星号的目录)
'searchterm'
:搜索内容
./
:从当前目录开始。
答案 2 :(得分:47)
怎么样:
find . -name '*.h' -o -name '*.cpp' -exec grep "CP_Image" {} \; -print
答案 3 :(得分:44)
grep -rnw "some thing to grep" --include=*.{module,inc,php,js,css,html,htm} ./
答案 4 :(得分:15)
HP和Sun服务器上没有-r选项,这种方式适用于我的HP服务器
find . -name "*.c" | xargs grep -i "my great text"
-i用于不区分大小写的字符串搜索
答案 5 :(得分:11)
由于这是查找文件的问题,让我们使用find
!
使用GNU查找,您可以使用-regex
选项在扩展名为.h
或.cpp
的目录树中查找这些文件:
find -type f -regex ".*\.\(h\|cpp\)"
# ^^^^^^^^^^^^^^^^^^^^^^^
然后,只需在每个结果上执行grep
:
find -type f -regex ".*\.\(h\|cpp\)" -exec grep "your pattern" {} +
如果您没有找到此发布版本,则必须使用Amir Afghani's之类的方法,使用-o
连接选项(名称以{{1结尾) }或.h
):
.cpp
如果您确实想使用find -type f \( -name '*.h' -o -name '*.cpp' \) -exec grep "your pattern" {} +
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
,请按照grep
指示的语法进行操作:
--include
答案 6 :(得分:7)
最简单的方法是
list
答案 7 :(得分:3)
我知道这个问题有点陈旧,但我想分享一下我通常用来查找 .c 和 .h 文件的方法:
tree -if | grep \\.[ch]\\b | xargs -n 1 grep -H "#include"
或者如果您还需要行号:
tree -if | grep \\.[ch]\\b | xargs -n 1 grep -nH "#include"
答案 8 :(得分:2)
ag
(银色搜索者)的语法非常简单
-G --file-search-regex PATTERN
Only search files whose names match PATTERN.
所以
ag -G *.h -G *.cpp CP_Image <path>
答案 9 :(得分:2)
以下答案很好。
grep -r -i --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP email@domain.com
但可以更新为:
grep -r -i --include \*.{h,cpp} CP_Image ~/path[12345] | mailx -s GREP email@domain.com
哪个更简单。
答案 10 :(得分:1)
应该写&#34; -exec grep&#34;对于每个&#34; -o -name&#34;
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" {} \;
选项&#39; -Hn&#39;显示文件名和行。
答案 11 :(得分:0)
如果您要从其他命令的输出中过滤掉扩展名,例如“ git”:
files=$(git diff --name-only --diff-filter=d origin/master... | grep -E '\.cpp$|\.h$')
for file in $files; do
echo "$file"
done