2014-01-23 121 views
0

我想從提供的文件夾中計算所有文件和目錄,包括子目錄中的文件和目錄。我已經寫了一個腳本,將準確計數的文件和目錄的數量,但它不處理任何想法的子目錄? 我想這樣做,而無需使用FIND命令計算提供的文件夾中的文件和目錄的總數,包括子目錄及其文件

#!/bin/bash 

givendir=$1 
cd "$givendir" || exit 

file=0 
directories=0 

for d in *; 
do 
if [ -d "$d" ]; then 
    directories=$((directories+1)) 
else 
    file=$((file+1)) 
fi 
done 

echo "Number of directories :" $directories 
echo "Number of file Files :" $file 
+0

哦,還有一件事我不想使用find命令來做。 – latitude8848

回答

1

使用發現:

echo "Number of directories:   $(find "$1" -type d | wc -l)" 
echo "Number of files/symlinks/sockets: $(find "$1" ! -type d | wc -l)" 

使用普通外殼和遞歸:

#!/bin/bash                        

countdir() {                        
    cd "$1"                         
    dirs=1                         
    files=0                         

    for f in *                        
    do                          
    if [[ -d $f ]]                       
    then                         
     read subdirs subfiles <<< "$(countdir "$f")"               
     ((dirs += subdirs, files += subfiles))                
    else                         
     ((files++))                      
    fi                          
    done                          
    echo "$dirs $files"                      
}                           

shopt -s dotglob nullglob                     
read dirs files <<< "$(countdir "$1")"                  
echo "There are $dirs dirs and $files files"  
+0

+1! -type d' – anubhava

+0

我想這樣做,而不使用find ...我想學習它的困難.. – latitude8848

+0

@ latitude8848:將是什麼樣的學習?正確使用正確的工具是學習IMO的最佳策略。 – anubhava

0

find "$1" -type f | wc -l會給你的文件,find "$1" -type d | wc -l目錄

我的快速和骯髒的shell會讀

#!/bin/bash 

test -d "$1" || exit 
files=0 

# Start with 1 to count the starting dir (as find does), else with 0 
directories=1 

function docount() { 
    for d in $1/*; do 
     if [ -d "$d" ]; then 
       directories=$((directories+1)) 
      docount "$d"; 
     else 
       files=$((files+1)) 
     fi 
    done 
} 

docount "$1" 
echo "Number of directories :" $directories 
echo "Number of file Files :" $files 

但它記:在一個項目我的生成文件夾中,有相當一些差異:

  • 發現:6430個迪爾斯,74377非迪爾斯
  • 我的腳本:6032個迪爾斯,71564非迪爾斯
  • @ thatotherguy的腳本:6794個迪爾斯,76862非迪爾斯

我認爲這與大量的鏈接,隱藏文件等有關,但我懶得調查:find是首選工具。

+0

偉大的腳本工作正常。當我在計算機上運行它時,輸出與查找命令類似。謝謝您的幫助 – latitude8848

0

下面是一些一行命令,工作沒有找到:

數量的目錄:ls -Rl ./ | grep ":$" | wc -l

號文件:ls -Rl ./ | grep "[0-9]:[0-9]" | wc -l

說明: ​​列出的所有文件和目錄遞歸,每行一行。

grep ":$"只找到最後一個字符爲':'的結果。這些都是目錄名稱。

grep "[0-9]:[0-9]"匹配時間戳的HH:MM部分。時間戳只顯示在文件上,而不是目錄。如果你的時間戳格式不同,那麼你需要選擇一個不同的grep。

wc -l統計與grep匹配的行數。

相關問題