如何递归地grep所有目录和子目录?
find . | xargs grep "texthere" *
如何递归地grep所有目录和子目录?
find . | xargs grep "texthere" *
当前回答
grep-r“texthere”。(通知期结束)
(^信用:https://stackoverflow.com/a/1987928/1438029)
澄清:
grep-r“texthere”/(递归地grep所有目录和子目录)
grep-r“texthere”。(递归地grep这些目录和子目录)
grep递归
grep[选项]模式[文件…][选项]-R、 -R,--递归递归地读取每个目录下的所有文件。这相当于-d recurse或--directories=recurse选项。http://linuxcommand.org/man_pages/grep1.html
grep帮助
$grep--帮助
$ grep --help |grep recursive
-r, --recursive like --directories=recurse
-R, --dereference-recursive
选择
确认(http://beyondgrep.com/)
银(http://github.com/ggreer/the_silver_searcher)
其他回答
也:
find ./ -type f -print0 | xargs -0 grep "foo"
但grep-r是更好的答案。
注意这个发现-当查找匹配的文件太多时,键入f | xargs grep任何类型的解决方案都会遇到“Argument list to long”错误。
最好的选择是grep-r,但如果不可用,请使用find-键入f-exec grep-H whatever{}\;相反
有关可用标志的列表:
grep --help
返回当前目录中此处的regexp文本的所有匹配项,以及相应的行号:
grep -rn "texthere" .
返回文本的所有匹配项,从根目录开始,具有相应的行号,忽略大小写:
grep -rni "texthere" /
此处使用的标志:
-r递归-n带输出的打印行号-我不理这个案子
这里有一个递归(使用bash和sh进行了少量测试)函数,它遍历给定文件夹($1)的所有子文件夹,并使用grep搜索给定文件($2)中的给定字符串($3):
$ cat script.sh
#!/bin/sh
cd "$1"
loop () {
for i in *
do
if [ -d "$i" ]
then
# echo entering "$i"
cd "$i"
loop "$1" "$2"
fi
done
if [ -f "$1" ]
then
grep -l "$2" "$PWD/$1"
fi
cd ..
}
loop "$2" "$3"
运行它和示例输出:
$ sh script start_folder filename search_string
/home/james/start_folder/dir2/filename
这是在我当前的机器上(windows 7上的git bash)适用于我的案例的例子:
find ./ -type f -iname "*.cs" -print0 | xargs -0 grep "content pattern"
对于带有空格的路径,我总是忘记-print0和-0。
编辑:我的首选工具现在是ripgrep:https://github.com/BurntSushi/ripgrep/releases . 它真的很快,并且有更好的默认值(比如默认情况下的递归)。与我的原始答案相同的示例,但使用了ripgrep:rg-g“*.cs”“content pattern”