计算目录树叶子中的文件

Ame*_*ina 5 zsh files

我想出了以下代码段来计算每个子目录中的文件:

for x (**/*(/)); do print $x; find $x -maxdepth 1 -type f | wc -l; done
Run Code Online (Sandbox Code Playgroud)

该命令输出连续的对(一个在另一个下面)如下:

directory_name
# of files
Run Code Online (Sandbox Code Playgroud)

我想将上面的代码更改为:

  • 在同一行上打印每个匹配项(即directory_name ':' # of files
  • 如果文件夹是目录树中的叶子(即它们没有任何子文件夹),则仅计算文件。

我怎样才能做到这一点?

Tim*_*edy 4

尝试这个:

for dir in $( gfind . -type d -print ); do files=$( find $dir -maxdepth 1 -type f | wc -l ); echo "$dir : $files"; done
Run Code Online (Sandbox Code Playgroud)

或者,在脚本中,您可以有更多的灵活性:

#!/usr/bin/ksh

# pass in the directory to search on the command line, use $PWD if not arg received
rdir=${1:-$(pwd)}

# if $rdir is a file, get it's directory
if [ -f $rdir ]; then
    rdir=$(dirname $rdir)
fi

# first, find our tree of directories
for dir in $( gfind $rdir -type d -print ); do
    # get a count of directories within $dir.
    sdirs=$( find $dir -maxdepth 1 -type d | wc -l );
    # only proceed if sdirs is less than 2 ( 1 = self ).
    if (( $sdirs < 2 )); then 
        # get a count of all the files in $dir, but not in subdirs of $dir)
        files=$( find $dir -maxdepth 1 -type f | wc -l ); 
        echo "$dir : $files"; 
    fi
done
Run Code Online (Sandbox Code Playgroud)

#!/usr/bin/zsh我使用 ksh 作为 shell 脚本,但它与, 或 一起使用也同样有效/usr/bin/bash