如何使用 bash 计算路径中的目录数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4842130/
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
How do I count the number of directories in a path using bash?
提问by fent
I'm using
我正在使用
DIRS=$(find . -type d)
to get get all directories recursively. Now I need to look at that list and print only the paths that have more than n number of directories. So I need to search for the '/' character in the path, but the methods I'm using to search for it aren't working.
递归获取所有目录。现在我需要查看该列表并仅打印具有超过 n 个目录的路径。所以我需要在路径中搜索“/”字符,但是我用来搜索它的方法不起作用。
回答by Thomas
Would this also work for you?
这对你也有用吗?
DIRS=$(find . -type d -mindepth $n)
The command find .simply lists all files and directories in the current directory, recursively. Using -type d, we restrict it to list directories only. Using -mindepth $n, we require that each directory it at depth at least $n(set e.g. n=2, or just substitute the number directly instead of $n). See man findfor more information.
该命令find .只是递归地列出当前目录中的所有文件和目录。使用-type d,我们将其限制为仅列出目录。使用-mindepth $n,我们要求每个目录至少在深度$n(设置例如n=2,或直接替换数字而不是$n)。请参阅man find以获取更多信息。
The $(...)construct runs the given command and is substituted by its output; it is roughly equivalent to `...`. Finally, this output is assigned to the DIRSvariable.
该$(...)构造运行给定的命令并由其输出替换;它大致相当于`...`. 最后,将此输出分配给DIRS变量。
回答by Patrick
A clean way of doing this would be to do
这样做的一个干净的方法是做
find . -type d -links +2
找 。-type d -links +2
This will find all directories with more than 2 hard links. A subdirectory adds one hardlink to its parent directory, plus you have a hard link for '.' and '..'.
这将找到具有 2 个以上硬链接的所有目录。子目录向其父目录添加一个硬链接,此外您还有一个“.”的硬链接。和 '..'。

