すべてのサブディレクトリのファイル数を計算し、その数を合計する方法

すべてのサブディレクトリのファイル数を計算し、その数を合計する方法

各ディレクトリ/サブディレクトリのファイル数を数え、それらを一緒に追加して合計を取得し、他のディレクトリと比較することができます。

#!/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がない場合は、このような操作にBash 3連想配列を使用するのではなく、Perl、Python、Rubyなどに切り替えることをお勧めします。

contentこれは、ツリーに同じファイルが含まれていることを示すのではなく、../oldcontent各サブディレクトリに同じ数のファイルが含まれていることを意味します。各ツリー内のファイルの変更を検出するには、以下を使用する必要があります。rsyncそれとも私」MD5ディレクトリ「Unix.SEのソリューション。

おすすめ記事