2014-01-23 120 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匹配的行数。

相关问题