ディレクトリツリーリーフ内のファイル数の計算

ディレクトリツリーリーフ内のファイル数の計算

各サブディレクトリのファイル数を計算するために、次のコードスニペットを考えました。

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

このコマンドは、次のように連続したペア(下のペア)を出力します。

directory_name
# of files

上記のコードを次のように変更したいと思います。

  • 同じ行に各一致を印刷します(例directory_name ':' # of files:)。
  • ファイルは、フォルダがディレクトリツリーにある場合(つまり、サブフォルダがない場合)にのみ計算されます。

どうすればいいですか?

ベストアンサー1

この試み:

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

あるいは、スクリプトでより柔軟性を持つことができます。

#!/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

#!/usr/bin/zshkshをシェルスクリプトとして使用していますが、またはでもうまく機能します/usr/bin/bash

おすすめ記事