#!/bin/sh
#
# Recursively counts number of files per directory. Optionally by
# a egrep expression.

if [ -z "$1" ]; then
  echo "Usage: $0 <directory-path> [<egrep-expression>]"
  exit 1
elif [ -d "$1" ]; then
  DIR="$1"
else
  echo "Error: $1 is not a directory."
  exit 1
fi

if [ "$2" ]; then
  EXPR="$2"
  find "$DIR" -type f | egrep "$EXPR" | xargs -I% dirname % | sort | uniq -c | sort -n
else
  find "$DIR" -type f | xargs -I% dirname % | sort | uniq -c | sort -n
fi