Tuesday, July 11, 2006

Linux : Counting files per directory with Bash command

With commands, you can do many intricate things. Following command which is a small script, counts the number of .htm files in each subdirectory upto depth 2 of the current working directory.

for x in `find . -type d -maxdepth 2`; do y=`find $x -name "*.htm" | wc -l`; if [ $y != 0 ]; then echo $x - $y; fi done

This command is useful for webmasters who spend some time once in a while to figure out number of files in each of the website's subdirectories.

Notes
  1. The value of -maxdepth may be changed as needed
  2. The above command uses current directory (find . -type ...). The dot may be replaced by path of a directory of which the stats is needed.
  3. "*.htm" part of the filename may also be replaced with whatever you want

5 comments:

Heen Kweix' said...

Wow, after trying my on my own and googling I haven't been able to find a way to do this until I ran into your blog. The only problem now is if the dirs have spaces in them. Thanks.

Ketan said...

Here's the solution.

for loop uses $IFS variable to determine what the field separators are. By default $IFS is set to the space character. There are multiple solutions to this problem.

The solution is to set the $IFS variable.

Like the following

################################
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for x in `find . -maxdepth 2 -type d`;
do

y=`find $x -name "*.htm" | wc -l`;

if [ $y != 0 ];
then echo $x - $y;
fi

done;

### restore $IFS
IFS=$SAVEIFS
#############################

Heen Kweix' said...

That worked great. What I ended up doing was cheating and pointing jdiskreport at a samba share. It gave an excellent report in many different ways.

But this code will be useful when we need it quick and don't want to mess with mounting a share and running something like jdiskreport. Thanks for the help.

Ketan said...

Hello Heen,

I'm glad that the code helped you :-)

Casino Neteller said...

Sure version :)