我正在编写一个脚本,以grep某些目录:

{ 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.example

如何将结果限制为扩展名.h和.cpp?


当前回答

grep -rnw "some thing to grep" --include=*.{module,inc,php,js,css,html,htm} ./

其他回答

你应该为每个"-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服务器上产生了问题。这对我来说非常有效:

grep -r --include=\*.txt 'searchterm' ./

...或者不区分大小写的版本…

grep -r -i --include=\*.txt 'searchterm' ./

grep:命令 - r:递归 我:忽略大小写 ——include: all *.txt:文本文件(转义为\以防你有一个目录的文件名中有星号) 'searchterm':搜索什么 ./:从当前目录开始。

源码:PHP革命:如何在Linux中Grep文件,但只有某些文件扩展名?

如果你想从另一个命令的输出中过滤掉扩展名。“git”:

files=$(git diff --name-only --diff-filter=d origin/master... | grep -E '\.cpp$|\.h$')

for file in $files; do
    echo "$file"
done

下面是我通常用来查找。c和。h文件的一个方法:

tree -if | grep \\.[ch]\\b | xargs -n 1 grep -H "#include"

或者如果你也需要行号:

tree -if | grep \\.[ch]\\b | xargs -n 1 grep -nH "#include"

只需使用——include参数,就像这样:

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

这应该是你想要的。

以下是HoldOffHunger的回答:

grep:命令 - r:递归 我:忽略大小写 -n:每个输出行之前都有相应的行号 ——包含\*.cpp: all *.cpp: c++文件(使用\转义以防文件名中有星号的目录) ./:从当前目录开始。