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

其他回答

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

最简单的方法是:

find . -type  f -name '*.extension' 2>/dev/null | xargs grep -i string

添加2>/dev/null来终止错误输出。

要在整个系统中包含更多的文件扩展名和密码grep:

find / -type  f \( -name '*.conf' -o -name "*.log" -o -name "*.bak" \) 2>/dev/null |
xargs grep -i password

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

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

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

其中一些答案似乎语法太多,或者在我的Debian服务器上产生了问题。这对我来说非常有效:

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

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

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

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

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

这个答案很好:

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

但可以更新为:

grep -r -i --include \*.{h,cpp} CP_Image ~/path[12345] | mailx -s GREP email@domain.example

这可以更简单。