Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Search 递归使用grep_Search_Full Text Search_Grep_Cygwin - Fatal编程技术网

Search 递归使用grep

Search 递归使用grep,search,full-text-search,grep,cygwin,Search,Full Text Search,Grep,Cygwin,grep能够使用-r选项进行递归搜索。但是,我想知道grep是否能够针对指定数量的子文件夹级别递归搜索查询字符串。例如,我有一个文件夹root,其中包含文件夹parent1、parent2、…、parentN。每个父文件夹都有普通的文本文件和文件夹,称为child1、child2、…、childM。我想从根级别运行grep,在父文件夹中搜索文件,而不查看子文件夹。有什么简单的方法可以做到这一点吗?您可以尝试以下方法: grep: --exclude=GLOB Ski

grep能够使用
-r
选项进行递归搜索。但是,我想知道grep是否能够针对指定数量的子文件夹级别递归搜索查询字符串。例如,我有一个文件夹
root
,其中包含文件夹
parent1、parent2、…、parentN
。每个父文件夹都有普通的文本文件和文件夹,称为
child1、child2、…、childM
。我想从根级别运行grep,在父文件夹中搜索文件,而不查看子文件夹。有什么简单的方法可以做到这一点吗?

您可以尝试以下方法:

grep

 --exclude=GLOB
              Skip files whose base name matches GLOB  (using
              wildcard  matching).   A file-name  glob  can  use *,
              ?, and [...]  as wildcards, and \ to quote a wildcard
              or backslash character literally.

       --exclude-from=FILE
              Skip files whose base name matches any of the file-name
              globs  read  from FILE (using wildcard matching as
              described under --exclude).

       --exclude-dir=DIR
              Exclude directories matching the pattern DIR from
              recursive searches.
或者使用此
find | xargs grep

使用find,您可以定义级别

编辑

在linux/unix世界中,一个命令到另一个命令的管道输出非常常见。我打赌你每天都这么做

echo "abc"|sed 's/a/x/'
find . -name "*.pyc" |xargs rm
awk 'blahblah' file | sort |head -n2 
tree|grep 'foo'
mvn compile|ack 'error'
...
请注意,并非上述所有示例都是有效的。它们只是一些例子。

因为,你不能用一个直接的
grep
;它根本不够强大。诀窍是使用
find
确定要搜索的文件,并将
find
生成的文件列表传递给
grep

如果运行
manfind
,您将获得一个包含
find
所使用的许多选项的手册页。我们感兴趣的是
-maxdepth

让我们建立我们需要的指挥权。在每个阶段运行命令以查看其外观:

  • 查找。
    将列出当前文件夹(
    )或任何子文件夹中存在的所有文件和文件夹

  • find-maxdepth 1将列出当前文件夹中的所有文件和文件夹<代码>查找-maxdepth 2同样会列出当前文件夹和任何直接子文件夹中的所有文件和文件夹。等等

  • 请注意,我们也列出了文件夹;我们不希望这样,因为
    grep
    无法搜索文件夹本身,只能搜索文件夹中的文件。添加
    -键入f
    仅获取列出的文件:
    查找-maxdepth 2-类型f

现在我们知道了要搜索的文件,我们需要获得
grep
来搜索这些文件。执行此操作的标准方法是使用
xargs

find . -maxdepth 2 -type f | xargs grep <text-to-search-for>

(以
+
结尾和
之间的区别在这里没有区别。如果你感兴趣,它是在
人查找
,但简短的版本是
+
更快,但意味着你只能在命令中有一个
{}

你想做一些类似的事情:find/path/to/find-name“nameoff文件”还是要对每个文件进行cat以检查字符串?谢谢您的快速回答。你能解释一下|在你的例子中意味着什么吗。我知道它可以用于将输出管道化到dest,但我不明白将输出管道化到其他命令有什么意义。无论如何,我正在尝试你的解决方案,很快就会接受你的答案。
find . -type f -maxdepth 2 -exec grep <text-to-search-for> {} +