如何递归地grep所有目录和子目录?
find . | xargs grep "texthere" *
如何递归地grep所有目录和子目录?
find . | xargs grep "texthere" *
当前回答
如果您正在从目录结构中查找所有文件中的特定内容,您可以使用find,因为它更清楚您在做什么:
find -type f -exec grep -l "texthere" {} +
注意,-l(l的小写)显示包含文本的文件的名称。如果要打印匹配项本身,请将其删除。或者使用-H将文件与匹配项一起获取。总之,其他备选方案包括:
find -type f -exec grep -Hn "texthere" {} +
其中-n打印行号。
其他回答
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
在IBM AIX Server(操作系统版本:AIX 5.2)中,使用:
find ./ -type f -print -exec grep -n -i "stringYouWannaFind" {} \;
这将打印出文件中的路径/文件名和相对行号,如:
./inc/xxxx_x.h
2865:/**描述:stringYouWanna查找*/
无论如何,这对我来说很有用:)
这里有一个递归(使用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
如果您正在从目录结构中查找所有文件中的特定内容,您可以使用find,因为它更清楚您在做什么:
find -type f -exec grep -l "texthere" {} +
注意,-l(l的小写)显示包含文本的文件的名称。如果要打印匹配项本身,请将其删除。或者使用-H将文件与匹配项一起获取。总之,其他备选方案包括:
find -type f -exec grep -Hn "texthere" {} +
其中-n打印行号。
grep -r "texthere" .
第一个参数表示要搜索的正则表达式,而第二个参数表示应该搜索的目录。在这种情况下。表示当前目录。
注意:这适用于GNUgrep,在某些平台(如Solaris)上,您必须特别使用GNUgrep而不是传统实现。对于Solaris,这是ggrep命令。