How do you print number of files for each folder in a directory [Linux]

I have been annoyed by the fact that I couldn’t easily print file count for all of the folders in certain directory.  Most of the time I just want to see what space each folder is using (du -hs *) but there are times when I need to know how many files are in each folder (checking cache folder, session folders etc).   So I whipped together a command line which does just that for me:

for i in `find -maxdepth 1 -type d`; do  echo -n $i " ";find $i|wc -l; done

I am sure there are many different ways to show file count for each folder in a directory and I am curious to see what people do so please do post comments with what you do.

Above command is pretty simple and can be expanded to do whatever you need.  For example, you can throw it into a bash script and be able to pass parameters.  For example:  count_files /home/  In this case your command line would look like:

for i in `find /home/ -maxdepth 1 -type d`; do  echo -n $i " ";find $i|wc -l; done

only difference would be that /home/ would be argument you passed and therefore will be $1.  Here is a sample script for above example:

#!/bin/bash
for i in `find $1 -maxdepth 1 -type d`; do
echo -n $i " ";
find $i|wc -l;
done

————————————-
DISCLAIMER: Please be smart and use code found on internet carefully. Make backups often. And yeah.. last but not least.. I am not responsible for any damage caused by this posting. Use at your own risk.

3 thoughts on “How do you print number of files for each folder in a directory [Linux]

  1. Sunny Walia Post author

    Thanks Scott but that gives disk usage for that particular folder which is not what I was looking. I was looking # of files within each folder under specific directory.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>