HOWTO: Sort files/folders in current directory by the number of files they contain

ls | while read i; do
  echo -e "`find "$i" | wc | gawk '{print $1}'` \t$i"
done | sort -n

The line is broken up for readability, but can be on one line. Essentially, this runs through every file in the current directory, finds the number of files in that file (always 1) or directory then echos it and the file name. At the end, it does a numerical sort with the largest number of files last. The actual number of files are generated using ‘find’, running it through ‘wc’ (word count), then taking the first number (which is the number of lines in the stream) using ‘gawk’.

If you want to use this often, consider adding the following functions to your ‘~/.bashrc':

sort_by_num_files() {
  local target=$1
  if [ -z "$target" ]; then 
    target=`pwd`
  fi

  ls $target | while read i; do
      echo -e "`get_num_files_in "$target/$i"` \t$i"
  done | sort -n
}

get_num_files_in() {
  local target=$1
  if [ -z "$target" ]; then
    echo "Must provide a target."
    return 1
  fi

  find "$target" | wc | gawk '{print $1}'
}

Hope you enjoy!

-Leo

CREDITS: