如何计算所有子目录中的文件数量并将计数加在一起

如何计算所有子目录中的文件数量并将计数加在一起

我试图计算每个目录/子目录中的文件数量,将它们加在一起并得到总数,然后我可以将其与另一个目录进行比较:

#!/bin/bash

echo "Checking directories for proper extensions"

for LOOP in 1 2 3 4; 
do
    if [[ $LOOP -eq 1 ]]; then
        find ./content/documents -type f ! \( -name \*.txt -o -name \*.doc -o -name \*.docx \)
        count1=$(find ./content/documenets -type f) | wc -l
        #count number of files in directory and add to counter
    elif [[ $LOOP -eq 2 ]]; then
        find ./content/media -type f ! -name \*.gif 
        count2=$(find ./content/media -type f) | wc -l
        #count number of files in directory and add to counter
    elif [[ $LOOP -eq 3 ]]; then
        find ./content/pictures -type f ! \( -name \*.jpg -o -name \*.jpeg \) 
        count3=$(find ./content/pictures -type f) | wc -l
        #count number of files in directory and add to counter
    else
        count4=$(find /home/dlett/content/other -type f) | wc -l
        #count number of files in directory and add to counter
    fi

    #list the files in each subdirectory in catalog and put into an array
    #count the number of items in the array
    #compare number of item in each array
    #if the number of item in each array doesn't equal 
        #then print and error message
    content_Count=$(( count1+count2+count3+count4 ))
    echo $content_Count
done

答案1

您的问题没有说明以前的已知良好值来自哪里。我假设您有一个与content名为 的树平行的树../oldcontent。调整以适应:

#!/bin/bash

echo "Checking directories for proper extensions"

for d in documents media pictures other
do
    nfc=$(find content/$d -type f | wc -l)
    ofc=$(find ../oldcontent/$d -type f | wc -l)
    if [ $nfc -eq $ofc ]
    then
         echo The "$d" directory has as many files as before.
    elif [ $nfc -lt $ofc ]
    then
         echo There are fewer files in the content directory than before.
    else
         echo There are more files in the content directory than before.
    fi
done

这段代码要短得多,因为它不会尝试find在每个循环上给出不同的命令。如果你真的需要它,你可以使用关联数组将目录名称和find参数配对:

declare -A dirs=(
    [documents]="-name \*.txt -o -name \*.doc -o -name \*.docx" 
    [media]="-name \*.gif"
    [pictures]="-name \*.jpg -o -name \*.jpeg"
    [other]=""
)

那么for循环就变成:

for d in "${!dirs[@]}"
do
    nfc=$(find content/$d -type f ${dirs[$d]} | wc -l)
    ofc=$(find ../oldcontent/$d -type f ${dirs[$d]} | wc -l)

...

不过,这只适用于 Bash 4 及更高版本。 Bash 3 中有一个不太强大的关联数组机制,但它在设计上几乎被破坏了。如果您手头没有 Bash 4,我鼓励您切换到 Perl、Python 或 Ruby 之类的东西,而不是尝试将 Bash 3 关联数组用于此类操作。

请注意,这并不告诉您该content树包含与 相同的文件../oldcontent,只是每个子目录具有相同数量的文件。如果您尝试检测每棵树中文件的更改,则需要使用rsync或者我的“MD5 目录“ Unix.SE 上的解决方案。

相关内容