我正在编写#0某些目录的脚本:
{ 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
如何将结果限制为扩展#0和#1?
用途:
find . -name '*.h' -o -name '*.cpp' -exec grep "CP_Image" {} \; -print
只需使用--include参数,如下所示:
--include
grep -inr --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP email@domain.example
这应该做你想要的。
下面的解释来自饥饿的答案:
grep:命令
grep
-r:递归
-r
-i:默认大小写
-i
-n:每个输出行前面都有它在文件中的相对行号
-n
--include \*.cpp:所有*. cpp:C++文件(以防文件名中有星号的目录,请使用\转义)
--include \*.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'显示文件名和行。
这是我通常用于查找. c和. h文件的方法:
tree -if | grep \\.[ch]\\b | xargs -n 1 grep -H "#include"
或者如果你也需要行号:
tree -if | grep \\.[ch]\\b | xargs -n 1 grep -nH "#include"
grep -rnw "some thing to grep" --include=*.{module,inc,php,js,css,html,htm} ./
在HP和Sun服务器上没有任何-r选项,但这种方式在我的HP服务器上适用:
find . -name "*.c" | xargs grep -i "my great text"
-i用于不区分大小写的字符串搜索。
其中一些答案似乎语法太重,或者它们在我的Debian服务器上产生了问题。这对我来说非常有效:
grep -r --include=\*.txt 'searchterm' ./
…或不区分大小写的版本…
grep -r -i --include=\*.txt 'searchterm' ./
-i:忽略大小写
--include:所有*. txt:文本文件(用\转义,以防文件名中有星号的目录)
'searchterm':搜索什么
'searchterm'
来源:PHP革命:如何Grep文件在Linux,但只有某些文件扩展名?
由于这是找到文件的问题,让我们使用find!
find
使用GNU查找,您可以使用-regex选项在扩展名为.h或.cpp的目录树中查找这些文件:
-regex
.h
.cpp
find -type f -regex ".*\.\(h\|cpp\)"# ^^^^^^^^^^^^^^^^^^^^^^^
然后,它只是在其每个结果上执行grep的问题:
find -type f -regex ".*\.\(h\|cpp\)" -exec grep "your pattern" {} +
如果您没有这种查找分布,则必须使用类似于阿米尔阿富汗尼的的方法,使用-o连接选项(名称以#1或#2结尾):
-o
find -type f \( -name '*.h' -o -name '*.cpp' \) -exec grep "your pattern" {} +# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
如果你真的想使用grep,请遵循--include指示的语法:
grep "your pattern" -r --include=*.{cpp,h}# ^^^^^^^^^^^^^^^^^^^
最简单的方法是:
find . -type f -name '*.extension' 2>/dev/null | xargs grep -i string
添加2>/dev/null以终止错误输出。
2>/dev/null
要在整个系统中包含更多文件扩展名和grep密码:
find / -type f \( -name '*.conf' -o -name "*.log" -o -name "*.bak" \) 2>/dev/null |xargs grep -i password
#0(银色搜索器)对此有非常简单的语法
-G --file-search-regex PATTERNOnly search files whose names match PATTERN.
所以
ag -G *.h -G *.cpp CP_Image <path>
这个答案很好:
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
哪一个可以更简单。
如果您想从另一个命令的输出中过滤掉扩展,例如“git”:
files=$(git diff --name-only --diff-filter=d origin/master... | grep -E '\.cpp$|\.h$') for file in $files; doecho "$file"done