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


当前回答

你应该为每个"-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”显示文件名和行。

其他回答

最简单的方法是:

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

你应该为每个"-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”显示文件名和行。

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

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

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

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

因为这是一个查找文件的问题,让我们使用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}
#                      ^^^^^^^^^^^^^^^^^^^