wc -lコマンドの出力の合計を数える

wc -lコマンドの出力の合計を数える

次のようなワークスペースツリーがあります:

/Directory
  /Dir1/file1, file2
  /Dir2/file3, file4
  /Dir3/file5, file6
...

dir 内の各ファイルの行数の合計をカウントしたいです。

このスクリプトはありますが、各ファイルの行数のみをカウントし、合計はカウントしません。

#!/bin/bash

find . -maxdepth 1 -mindepth 1 -type d | while read dir; do
  printf "%-25.25s : " "$dir"
  find "$dir" -type f | while read file; do
      linecount= cat $file | wc -l 
      echo "this file contains $linecount lnes"
  done 
done

答え1

私の解決策は次のようになります:

for d in */; do
    echo -n "$d : "
    sum=0
    for f in "$d"/*; do
        if [ -f "$f" ] ; then
            lines=$(wc -l "$f")
            sum=$((sum+lines))
        fi
    done
    echo $sum
done

初心者にとってはもう少し分かりやすいかもしれません。

答え2

呼び出し回数を最小限に抑えるwc:

find /Directory -type d -print0 | while read -d '' dir; do
    echo -n "$dir: "
    find "$dir" -type f -exec wc -l {} + | sed -n 's/\([0-9]\{1,\}\) total/\1/p' | paste -sd+ | bc
done

関連情報