Forum Moderators: bakedjake
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
or to exclude from the search hidden dirs/files:
find . -type f ¦ awk '!/\/\..*/ {dir=gensub(/(.+\/).+/,"\\1","g",$0); dir_list[dir]++} END {for (d in dir_list) printf "%s %s\n",d,dir_list[d]}' ¦ sort
awk '{
# $0 will contain relative path to the file
# we don't care about file name, so will strip it
# for details on gensub check awk man page
# so, variable "dir" will hold the directory name
dir=gensub(/(.+\/).+/,"\\1","g",$0);
# add directory name to the hash "dir_list"
# at the same time increase the counter by one
# for that directory name
dir_list[dir]++
END {
# read the hash and print values
# "d" will be directory name
# hash element "dir_list[d]" will be a number
# showing how many files are in that directory
for (d in dir_list)
printf "%s %s\n",d,dir_list[d]
}'
"sort" will sort output :)
Extra part in second line (one to exclude hidden files) says:
!/\/\..*/
what means: anything what has slash with following dot in a path consider as a hidden file/dir and ignore.
Thanks you for welcoming us :)
that is really sweet stuff!
i haven't used awk enough recently.
and i never thought about using find -type f that way.
i've always wondered what the ls option was to include the path and now i know...
=8)
gensub(/(.+\/).+/,"\\1","g");
I learned something new today! Thanks.