我不知道如何“简单地”获取没有子文件夹的文件夹数量。
我在 find
中发现了一些带有 -printf "%h\n"
的东西,但是我不确定这是做什么的。
最佳答案
要确定当前目录中不包含子文件夹的文件夹(不考虑隐藏的文件夹):
find . -maxdepth 1 -type d -execdir bash -c 'shopt -s nullglob; a=( "$1"/*/ ); ((${#a[@]}==0)); exit $?' _ {} \; -print
考虑隐藏的内容(当然不包括
.
和..
):find . -maxdepth 1 -type d -execdir bash -c 'shopt -s nullglob dotglob; a=( "$1"/*/ ); ((${#a[@]}==0)); exit $?' _ {} \; -print
如果您想递归到文件夹(即,还确定具有此属性的子文件夹),只需删除命令的 -maxdepth 1
部分即可。
当然还有其他方法:100% 纯 bash,或者更有趣的是,在 find
中使用 find
,如下所示:
find . -maxdepth 1 -type d \! -execdir sh -c 'find "$1" -mindepth 1 -type d -print -quit | read a' _ {} \; -print
请注意,这些方法对于包含有趣符号(空格、换行符、前导/尾随空格和换行符等)的文件名是 100%。
为了得到一个(某种)全面的答案,我想添加以下精彩的方法。 Thor指出在 this comment of the OP ,并指Ben Jackson的answer in another similar question我将在下面引用(经过改编):
[If your file system supports hardlinks] there is a much simpler solution that takes advantage of the fact that the parent directory links
..
from each subdirectory increase the link count of the directory by 1. A directory with no subdirectories has a link count of 2 (.
and the link from its own parent by its name). Thus a directory with no subdirectories has a link count of 2 and can be found with this command:find . -type d -links 2
It's not legal to make other hardlinks to a directory so there should be no false positives.
关于bash - 没有子文件夹的文件夹数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19731328/