我正在编写一个脚本,以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?


当前回答

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

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

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

其他回答

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

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

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

只需使用——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++文件(使用\转义以防文件名中有星号的目录) ./:从当前目录开始。

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

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

或者如果你也需要行号:

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

因为这是一个查找文件的问题,让我们使用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阿富汗尼的方法,使用-o来连接选项(名称以。h或。cpp结尾):

find -type f \( -name '*.h' -o -name '*.cpp' \) -exec grep "your pattern" {} +
#            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

如果你真的想使用grep,请遵循指示的语法——include:

grep "your pattern" -r --include=*.{cpp,h}
#                      ^^^^^^^^^^^^^^^^^^^

Use:

find . -name '*.h' -o -name '*.cpp' -exec grep "CP_Image" {} \; -print