Page is a not externally linkable
- Hardware and OS Related Technologies
-- Linux, Unix, and *nix like Operating Systems
---- Count files in a directory and each subdirectory


TimD - 8:04 am on Dec 30, 2008 (gmt 0)


The following script is based on one written by jjc_mn, posted in Sept 2006 (http://www.webmasterworld.com//linux/3087663.htm). Judging by its high ranking in a Google search, I'm guessing that it has been quite a popular question.

My version gets passed a directory name as a parameter. It then outputs a line for each sub-directory, showing the directory name (excluding the portion passed as a parameter), along with the number of files (tracks) within the directory.

Hopefully someone will find it useful. Many thanks to jjc_mn for providing the starting point.

#!/bin/bash
#counts files in subdirectories
#set -x

top_dir=$1
if [ -z $top_dir ]
then
echo "Directory path must be given"
exit -1
fi
if [ ! -d $top_dir ]
then
echo "Directory path given is not valid"
exit -2
fi
echo "Analysing files in $top_dir..."

date_stamp=`date +"%m%d%Y.%H%M%S"`
temp_file="temp.$date_stamp.txt"
done_loop=""
find $top_dir -type d ¦ sort > $temp_file

exec 3< $temp_file
until [ $done_loop ]
do
read <&3 myline
if [ $? != 0 ]
then
done_loop=1
continue
fi

dir_count=`find "$myline/." \( -name . -o -prune \) -type f ¦wc -l`
if [ $dir_count != 0 ]
then
short_name=${myline:${#top_dir}}
short_name=${short_name#/}
short_name=${short_name:=$top_dir}
count_desc="tracks"
if [ $dir_count = 1 ]
then
count_desc="track"
fi
echo "$short_name ($dir_count $count_desc)"
fi
done
rm $temp_file
#EOF


Thread source:: http://www.webmasterworld.com/linux/3816106.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com