I need to inspect all sub-directories and report how many files (without further recursion) they contain:
directoryName1 numberOfFiles
directoryName2 numberOfFiles
|
This does it in a safe and portable way. It won't get confused by strange filenames.
If you have a specific set of subdirectories you're interested in, you can replace the Why is this safe? (and therefore script-worthy) Filenames can contain any character except Using the Once you have the filename in a variable, you still have to avoid things like Newlines and spaces are also a problem. If Finally, filenames can contain newlines, so counting newlines in a list of filenames will not work; you'll get an extra count for every filename with a newline. To avoid this, don't count newlines in a list of files; instead, count newlines (or any other character) that represent a single file. This is why the |
|||||||
|
|
Based on a count script, Shawn's answer and a Bash trick to make sure even filenames with newlines are printed in a usable form on a single line:
The |
|||
|
|
|
By “without recursion”, do you mean that if
Note that the Ksh has a way to make patterns match dot files and to produce an empty list in case no file matches a pattern. So in ksh you can count regular files like this:
or all files simply like this:
Bash has different ways to make this simpler. To count regular files:
To count all files:
As usual, it's even simpler in zsh. To count regular files:
Change ¹ Note that each pattern matches itself, otherwise the results might be off (e.g. if you're counting files that start with a digit, you can't just do |
|||
|
|
|
Here's a "brute-force"-ish way to get your result, using
|
|||||
|
|
Assuming that you are looking for a standard Linux solution, a relatively straightforward way to achieve this is with
Where |
|||||||||||
|
findwhen Bash will do?(shopt -s dotglob; for dir in */; do all=("$dir"/*); echo "$dir: ${#all[@]}"; done): for all directories, count the number of entries in that directory (including hidden dot files, excluding.and..) – janmoesen Oct 23 '11 at 20:27