Every now and then there may arise a need of asking “How many files do I have under certain folders”?
First thing first, expression upfront:
find * -maxdepth 1 -type d | while read -r dir;
do
printf "%s:\t" "$dir";
find "$dir" -type f | wc -l
done
Here’s how it works: to break things up, commands used here include
findis a useful command for searching files/folders.-maxdepth 1will search subdirectories only one level down;-type dlooks for directories, and-type flooks for files;
- A
whileloop that ends when the condition is met, in this case, reaching the end ofdirvariable. readis a command that can read a single line from standard input, then splitting the input into words can may be used by other commands.-rdeactivates the unexpected behavior of breaking up long lines with a trailing backslash character (see here).
printfoutputs string of texts defined by user.%sis a specifier that outputs the entire argument in literal form;\tis a specifier to print out TAB and add some spacing;- Adding quotation marks is considered more robust, considering that some folder names may contain spaces that may confuse the execution.
wc -lreturns the counts
Try it yourself to see how the outputs look like, maybe tweak a little to make it work for your case, and put in a function so that you don’t have to code it up every time!