bash - 查找子目录中的最大文件数

标签 bash unix subdirectory

所以我正在尝试编写一个 bash 脚本,该脚本将查看指定文件夹中的所有子目录,并返回单个子目录中的最大文件数。这是我现在拥有的:

#!/bin/bash   
maxCount=0 
fileCount=0 
# script that writes out all the directories and how many files are in each directory

find ./testdata/ -maxdepth 1 -mindepth 1 -type d | while read dir; do  #loop all subdirectories    
fileCount= find "$dir" -type f | wc -l #count all the files in subdirectory

    if [ $fileCount -gt $maxCount ] #if the count is higher than the max     
    then
        maxCount= "$fileCount" #set the count equal to the max
    fi

    done

#print out how many messages are in the thread    
echo "$maxCount"

首先,变量 fileCount 设置不正确。 find "$dir"-type f | 的输出wc -l 仍被设置为标准输出,因此脚本不断返回零。

当前输出示例:

1
1
2
1
1
1
0

最后一个零是 echo "$maxCount"的输​​出

不太确定我做错了什么。谢谢!

使用 xfce4 终端

最佳答案

你可以用下面的命令做你想做的,它利用了 find-exec 选项

find ./testdata/  -maxdepth 1 -mindepth 1 -type d -exec bash -c 'find {} -type f | wc -l' \; | sort -n | tail -n 1

按照您的方法,这一行

fileCount= find "$dir" -type f | wc -l #count all the files in subdirectory

=find 之间不应该有空格并且你应该有一个Command Substitution将值分配给变量 fileCount,如下所示:

fileCount=$(find "$dir" -type f | wc -l)

如果你想坚持 for 循环:

find . -maxdepth 1 -mindepth 1 -type d | while read dir;do
    cnt=$(find ${dir} -type f | wc -l)
    echo ${cnt}   
done | sort -n | tail -n 1

关于bash - 查找子目录中的最大文件数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46901269/

相关文章:

regex - 在 Bash 中使用正则表达式检查电子邮件地址的正确性

bash - 在将 tee 发送到文件之前,如何从 tee 获取 "process"文本

c - 使用 C 语言编程的 Makefile

java - 将目录和子目录中的特定文件复制到 mac 中的目标文件夹中

html - 如何递归爬取url子目录?

linux - 如何通过ssh发送三个管道的数据?

bash - unix/bash 中是否有速率计算器实用程序?

bash/sh 嵌套转义序列

c - 如何使用 pthread、pthread_exit 将 * 转换为 double/float

bash - 如何删除目录以外的所有文件?