如何递归地grep所有目录和子目录?
find . | xargs grep "texthere" *
如何递归地grep所有目录和子目录?
find . | xargs grep "texthere" *
当前回答
如果您只想跟踪实际的目录,而不是符号链接,
grep -r "thingToBeFound" directory
如果您希望遵循符号链接以及实际目录(注意无限递归),
grep -R "thing to be found" directory
由于您正在尝试递归grep,以下选项可能对您也有用:
-H: outputs the filename with the line
-n: outputs the line number in the file
因此,如果您希望在当前目录或任何子目录中查找包含达斯·维德的所有文件,并捕获文件名和行号,但不希望递归遵循符号链接,则命令如下
grep -rnH "Darth Vader" .
如果你想在目录中找到所有提到的单词cat
/home/adam/Desktop/TomAndJerry
并且您当前在目录中
/home/adam/Desktop/WorldDominationPlot
如果您希望捕获字符串“cats”的任何实例的文件名而不是行号,并且希望递归在找到符号链接时遵循符号链接,您可以运行以下任一操作
grep -RH "cats" ../TomAndJerry #relative directory
grep -RH "cats" /home/adam/Desktop/TomAndJerry #absolute directory
资料来源:
运行“grep--help”
对符号链接的简短介绍,对于任何阅读此答案并被我提到的符号链接所迷惑的人:https://www.nixtutor.com/freebsd/understanding-symbolic-links/
其他回答
grep -r "texthere" .
第一个参数表示要搜索的正则表达式,而第二个参数表示应该搜索的目录。在这种情况下。表示当前目录。
注意:这适用于GNUgrep,在某些平台(如Solaris)上,您必须特别使用GNUgrep而不是传统实现。对于Solaris,这是ggrep命令。
这是在我当前的机器上(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”
要查找路径递归包含特定字符串的文件名,请使用以下命令对于UNIX:
find . | xargs grep "searched-string"
对于Linux:
grep -r "searched-string" .
在UNIX服务器上查找文件
find . -type f -name file_name
在LINUX服务器上查找文件
find . -name file_name
如果您只想跟踪实际的目录,而不是符号链接,
grep -r "thingToBeFound" directory
如果您希望遵循符号链接以及实际目录(注意无限递归),
grep -R "thing to be found" directory
由于您正在尝试递归grep,以下选项可能对您也有用:
-H: outputs the filename with the line
-n: outputs the line number in the file
因此,如果您希望在当前目录或任何子目录中查找包含达斯·维德的所有文件,并捕获文件名和行号,但不希望递归遵循符号链接,则命令如下
grep -rnH "Darth Vader" .
如果你想在目录中找到所有提到的单词cat
/home/adam/Desktop/TomAndJerry
并且您当前在目录中
/home/adam/Desktop/WorldDominationPlot
如果您希望捕获字符串“cats”的任何实例的文件名而不是行号,并且希望递归在找到符号链接时遵循符号链接,您可以运行以下任一操作
grep -RH "cats" ../TomAndJerry #relative directory
grep -RH "cats" /home/adam/Desktop/TomAndJerry #absolute directory
资料来源:
运行“grep--help”
对符号链接的简短介绍,对于任何阅读此答案并被我提到的符号链接所迷惑的人:https://www.nixtutor.com/freebsd/understanding-symbolic-links/
这里有一个递归(使用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