bash 可以“查找”或任何其他工具以广度优先搜索文件吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1086907/
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
Can 'find' or any other tool search for files breadth-first?
提问by flybywire
采纳答案by unwind
Yes, sort of.
是的,有点。
You can use the -depthoption to make it process a directory's contents before the directory itself. You can also use the -maxdepthoption to limit how many directories down it will drill.
您可以使用该-depth选项使其在目录本身之前处理目录的内容。您还可以使用该-maxdepth选项来限制向下钻取的目录数量。
回答by ephemient
Horrible hack, won't work with -0or any actions other than -print, inefficient, etc. etc…
可怕的黑客-0行为,除了-print效率低下等之外,无法使用或任何其他操作……
#!/bin/bash
i=0
while results=$(find -mindepth $i -maxdepth $i "$@") && [[ -n $results ]]; do
echo "$results"
((i++))
done
Basically this just runs
基本上这只是运行
find -mindepth 0 -maxdepth 0
find -mindepth 1 -maxdepth 1
find -mindepth 2 -maxdepth 2
…………………………………………………………………………
until findreturns non-zero status or prints nothing.
直到find返回非零状态或不打印任何内容。
回答by Jethro Yu
A breadth-first find using variable as its queue.
使用变量作为队列的广度优先查找。
Create bfs.sh
创建 bfs.sh
#!/bin/bash
queue=""
shift
while [ -n "$queue" ]
do
echo "$queue" | xargs -I'{}' find {} -mindepth 1 -maxdepth 1 $*
queue=`echo "$queue" | xargs -I'{}' find {} -mindepth 1 -maxdepth 1 -type d`
done
Make it executable:
使其可执行:
$ chmod u+x ./bfs.sh
$ chmod u+x ./bfs.sh
Then you can do a breadth-first find by:
然后您可以通过以下方式进行广度优先查找:
$ ./bfs.sh /path/to/somewhere -name foobar
$ ./bfs.sh /path/to/somewhere -name foobar
回答by nik
Use findwith the --maxdepthoption.
find与--maxdepth选项一起使用。
That is at the Directoriessection in your reference page; might find other options more suitable depending on your needs.
那是在您的参考页面的目录部分;可能会根据您的需要找到更合适的其他选项。
To achieve exact breadth first searching, you will need to loop with mixed --mindepthand --maxdepthoptions. But, I don't think it is necessary to be that exact, a depth limited search will usually suffice.
要实现精确的广度优先搜索,您需要使用混合--mindepth和--maxdepth选项循环。但是,我认为没有必要那么精确,深度有限的搜索通常就足够了。
回答by Duncan Grant
find . | awk '{FS = "/" ; print "", NF, $F}' | sort -n | awk '{print }' | xargs grep -d skip "search term"
It uses find to list all the files. The first awk command counts all the '/' characters. It sorts on the count and then drops the count column. Finally it uses xargs to grep the sorted list of files.
它使用 find 列出所有文件。第一个 awk 命令计算所有 '/' 字符。它对计数进行排序,然后删除计数列。最后它使用 xargs 来 grep 排序的文件列表。
It is really ugly.
它真的很丑。

