【问题标题】:Calculating the average number of files per folder计算每个文件夹的平均文件数
【发布时间】:2016-03-28 15:24:21
【问题描述】:

所以我正在编写一个 shell 脚本来计算用户选择的文件夹中的平均文件数量

我只是不太确定,如何解决这个问题。

首先,我们要设置用户文件夹选择

#!/bin/sh
# Script for folder info
#-------------------------------------------
WANTEDFOLDER=$PWD
cd
cd $1 #Go into the folder (first argument)
$WANTEDFOLDER/folderinfo.sh
# ------------------------------------------
echo "Selected directory: $PWD"

我添加了更多类似方式的命令,但这些命令正在运行,因此为了便于阅读,我不会在此处添加它们。

所以我想知道,我怎么可能计算位于指定目录的文件夹内的平均文件数。

为了更好地理解这一点,让我们设置一个示例目录

$ mkdir testdir
$ cd testdir
$ mkdir 1
$ mkdir 2
$ mkdir 3
$ cd 1
$ echo "hello" > wow.txt
$ cd ..
$ cd 2
$ echo "World"; > file.c
$ echo "file number 2" > twoinone.tex
$ cd ..
$ cd 3
$ echo "zzz" > z.txt
$ echo "zz2" > z2.txt
$ echo "zz3" ? z3.txt

好的,为了更好地说明,文件夹看起来像这样

所以首先,我们会做find . -type f

这应该打印以下结果

./1/wow.txt
./2/file.c
./2/twoinone.tex
./3/z.txt
./3/z2.txt
./3/z3.txt

现在我们在目录 1 中有 1 个文件,在 2 中有 2 个文件,在 3 中有 3 个文件。 所以计算平均值是 (1 + 2 + 3) / 3,结果为 2。

这也可以写成算法

(所有唯一文件的数量)/(所有唯一目录的数量)

一件事是在你的头脑中计算,另一件事是在实际的 shell 脚本中计算。

所以换句话说,我需要以某种方式转换为脚本,它会计算特定文件夹中的文件数量,存储它,将所有文件一起计算,然后最后除以唯一的数量目录。

所以要获得目录的数量,我们必须做到find . -type d | wc -l

要获取文件的数量,非常简单。我们将只使用find . -type f | wc -l

但我不知道的是,如何将这两个值存储在一个变量中,然后将它们相互分割

此外,理想情况下,我更喜欢以特定行的方式格式化代码

例如。 echo "Average Number of files: $(find . -type f | wc -l (somehow divide) find . -type d | wc -l)"

知道如何实现这一壮举吗?

【问题讨论】:

    标签: linux bash shell shebang


    【解决方案1】:

    也许这就是你要找的东西:

    echo $(( $(find . -type f | wc -l) / $(find . -type d | wc -l) ))
    

    【讨论】:

    • 谢谢,简单有效的解决方案。没有意识到我可以简单地对两个单独的命令使用算术表达式
    • $((..)) 允许您进行算术运算。请注意,它只是整数运算,因此如果您在 2 个目录中有 5 个文件,它会告诉您 2 而不是 2.5 作为平均值。
    • 非常正确。如果您期望非 int 结果,您可以使用dcawk 进行计算。
    【解决方案2】:

    1.) 真的有必要对所有目录中的平均文件数进行浮点估计吗?但是你问了这个问题,所以至少目前需要解决这个问题。

    #!/bin/bash
    
    NumFiles=0
    
    #Loop over all directories in the current location and count the files in each directory
    DirCount=0
    for d in */
    do
            FilesInDir=$(\ls -A $d|wc -l)
            echo "Number of files in directory $d is $FilesInDir"
            NumFiles=$(($NumFiles+$FilesInDir))
            DirCount=$(($DirCount + 1))
    done
    
    echo Final number of directories: $DirCount
    echo Total files in directories: $NumFiles
    
    if [ $DirCount -gt 0 ]; then
            AvgFiles=$(echo "$NumFiles/$DirCount" | bc -l)
            echo $AvgFiles
    fi
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-19
      • 1970-01-01
      • 2017-11-14
      • 1970-01-01
      • 2016-03-16
      相关资源
      最近更新 更多