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 protected]
如何将结果限制为扩展名
.h
和 .cpp
?
只需使用
--include
参数,如下所示:
grep -inr --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP [email protected]
这应该可以满足你的要求。
从下面HoldOffHunger的回答中获取解释:
grep
:命令
-r
:递归
-i
:忽略大小写
-n
:每个输出行前面都有其在文件中的相对行号
--include \*.cpp
:所有 *.cpp:C++ 文件(使用 \ 转义,以防万一您的目录的文件名中带有星号)
./
:从当前目录开始。
其中一些答案似乎语法过于繁重,或者它们在我的 Debian 服务器上产生了问题。这对我来说非常有效:
grep -r --include=\*.txt 'searchterm' ./
...或不区分大小写的版本...
grep -r -i --include=\*.txt 'searchterm' ./
grep
:命令-r
:递归-i
:忽略大小写--include
:所有 *.txt:文本文件(用 \ 转义以防万一您的目录的文件名中带有星号)'searchterm'
:要搜索什么./
:从当前目录开始。grep -rnw "some thing to grep" --include=*.{module,inc,php,js,css,html,htm} ./
用途:
find . -name '*.h' -o -name '*.cpp' -exec grep "CP_Image" {} \; -print
HP 和 Sun 服务器上没有任何
-r
选项,但这种方法在我的 HP 服务器上对我有用:
find . -name "*.c" | xargs grep -i "my great text"
-i
用于不区分大小写的字符串搜索。
纳尔逊的回答很好:
grep -r -i --include \*.h --include \*.cpp CP_Image ~/path[12345] |
mailx -s GREP [email protected]
但可以简化为:
grep -r -i --include \*.{h,cpp} CP_Image ~/path[12345] |
mailx -s GREP [email protected]
由于这是查找文件的问题,所以让我们使用
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 Afghani 的 的方法,使用
-o
连接选项(名称以 .h
或 .cpp
结尾):
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
以消除错误输出。
要在整个系统中包含更多文件扩展名和 grep 密码:
find / -type f \( -name '*.conf' -o -name "*.log" -o -name "*.bak" \) 2>/dev/null |
xargs grep -i password
ag
(银色搜索器)对此有非常简单的语法
-G --file-search-regex PATTERN
Only search files whose names match PATTERN.
所以
ag -G *.h -G *.cpp CP_Image <path>
您应该为每个“-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"
如果您想从另一个命令的输出中过滤掉扩展名,例如“吉特”:
files=$(git diff --name-only --diff-filter=d origin/master... | grep -E '\.cpp$|\.h$')
for file in $files; do
echo "$file"
done