bash 递归搜索给定名称的文件,并找到特定短语的实例并显示该文件的路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3538987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Recursively search for files of a given name, and find instances of a particular phrase AND display the path to that file
提问by AndyL
I have a bunch of folders and subfolders. Each one contains, amongst other things, a text file called index.yml
with useful data. I want to search through all of the different index.yml
files to find instances of a search string. I must be able to see a few lines of context and the directory of the index.yml
file that was found.
我有一堆文件夹和子文件夹。每个文件都包含一个包含index.yml
有用数据的文本文件。我想搜索所有不同的index.yml
文件以查找搜索字符串的实例。我必须能够看到几行上下文和index.yml
找到的文件的目录。
This almost works, but it doesn't give me the filename:
这几乎有效,但它没有给我文件名:
cat `find . -name 'index.yml'`| grep -i -C4 mySearchString
How can I do this and get the filename?
我怎样才能做到这一点并获得文件名?
I am stuck on Windows with using msys. Note I don't seem to have full GNU grep, so I can't run grep --exclude
or grep -R
as suggested in other SO questions.
我使用 msys 被困在 Windows 上。注意我似乎没有完整的 GNU grep,所以我无法运行grep --exclude
或grep -R
按照其他 SO 问题中的建议运行。
采纳答案by lesmana
try this:
尝试这个:
find -name "index.yml" -exec grep -i -H -C4 pattern {} \;
note: not actually tested under msys.
注意:未在 msys 下实际测试。
回答by jilles
One possibility (I don't know what msys accepts exactly):
一种可能性(我不知道 msys 到底接受什么):
find . -name index.yml -exec grep -i -C4 mySearchString /dev/null {} +
The /dev/null
serves to ensure there are at least two pathnames so that the pathname is printed with each match. The -H
option to grep has a similar effect.
在/dev/null
用于确保有至少两个路径名,使得该路径名被打印与每个匹配。该-H
选项的grep有类似的效果。
The -exec
...+
construct in find
causes multiple pathnames to be passed to a single instance of the command. If it is not implemented, you'll have to use -exec
...\;
.
该-exec
...+
结构的find
原因,多路径名传递到命令的单个实例。如果它没有实现,你将不得不使用-exec
... \;
。