bash - 没有子文件夹的文件夹数量

标签 bash unix find

我不知道如何“简单地”获取没有子文件夹的文件夹数量。 我在 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 Jacksonanswer 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/

相关文章:

bash - shell 脚本: Portable way to programmably obtain the CPU vendor on POSIX systems

linux - 为 bash 中的参数设置特定选项集

arrays - 在 mongoDB 中使用数组索引获取数组元素

bash - 如何在“找到(…)-exec(…){}\;”中的{}中替换字符串bash命令?

php - 错误替换 Bash : how to write a heredoc to a dynamically created file (variable)?

arrays - 在 bash 脚本中遍历 csv 文件中的数组的问题

c - 父进程退出后如何让子进程终止?

c - C中的中断系统调用

c - 共享内存程序在 c 中不起作用

linux - 需要 grep/awk/gawk 返回整个部分,尽管有断线