如何递归地grep所有目录和子目录?
find . | xargs grep "texthere" *
如何递归地grep所有目录和子目录?
find . | xargs grep "texthere" *
当前回答
也:
find ./ -type f -print0 | xargs -0 grep "foo"
但grep-r是更好的答案。
其他回答
另一种语法递归地grep Linux系统上所有文件中的字符串
grep-irn“字符串”
-r表示递归搜索,在给定目录和子目录中搜索指定字符串,在文件、程序等中查找指定字符串
-不区分大小写可用于添加大小写颠倒的字符串
-n打印指定字符串的行号
注意:这会将大量结果打印到控制台,所以您可能需要通过管道过滤输出,并删除不太有趣的信息,它还会搜索二进制程序,因此您可能需要过滤一些结果
只有文件名也很有用
grep -r -l "foo" .
只是为了好玩,如果@christangrant的答案太多而无法输入,可以快速搜索*.txt文件:-)
grep-r文本此处|grep.txt文件
如果您知道所需文件的扩展名或模式,另一种方法是使用--include选项:
grep -r --include "*.txt" texthere .
您还可以使用--exclude提及要排除的文件。
Ag
如果您经常搜索代码,Ag(银搜索器)是grep的一个更快的替代方案,它是为搜索代码而定制的。例如,默认情况下,它是递归的,并自动忽略.gitignore中列出的文件和目录,因此您不必一直向grep或find传递同样繁琐的排除选项。
ag是我现在最喜欢的实现方式github.com/ggreer/the_silver_searcher。它基本上与ack相同,但还有一些优化。
这是一个简短的基准。我在每次测试前清除缓存(cfhttps://askubuntu.com/questions/155768/how-do-i-clean-or-disable-the-memory-cache )
ryan@3G08$ sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
3
ryan@3G08$ time grep -r "hey ya" .
real 0m9.458s
user 0m0.368s
sys 0m3.788s
ryan@3G08:$ sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
3
ryan@3G08$ time ack-grep "hey ya" .
real 0m6.296s
user 0m0.716s
sys 0m1.056s
ryan@3G08$ sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
3
ryan@3G08$ time ag "hey ya" .
real 0m5.641s
user 0m0.356s
sys 0m3.444s
ryan@3G08$ time ag "hey ya" . #test without first clearing cache
real 0m0.154s
user 0m0.224s
sys 0m0.172s