Under bash in Ubuntu, I want to ls -lah
a directory and have it display file counts for directories recursively. That's to say I want it to count all files in the directories and their subdirectories.
Is this possible?
Under bash in Ubuntu, I want to ls -lah
a directory and have it display file counts for directories recursively. That's to say I want it to count all files in the directories and their subdirectories.
Is this possible?
I'm ignoring the request for the use of ls
here as the output from that utility, on most Unixes, is generally only suitable for looking at.
The following would use find
with bash
to count the number of names in each subdirectory of the current directory, recursively.
find . -type d -exec bash -O nullglob -O dotglob -c '
for dirpath do
set -- "$dirpath"/*
printf "%s:\t%d\n" "$dirpath" "$#"
done' bash {} +
It calls bash
with a batch of directory pathnames, and the in-line script iterates over the given batch and expands the *
globbing pattern in each. With the nullglob
and dotglob
shell options set, this expands to a list of (possibly hidden) names, and $#
is the length of that list.
If you just want the counts for the top-most directories in your current working directory:
shopt -s globstar nullglob dotglob
for dirpath in */; do
set -- "$dirpath"/**
printf '%s:\t%d\n' "$dirpath" "$#"
done
This is almost the same, except we no longer need to use find
. We use **
to glob all names under each directory recursively and then display the results as before.
In fact, we could modify this ever so slightly to recreate the first piece of code without the need for find
at all. Getting the count of names in each directory recursively:
shopt -s globstar nullglob dotglob
for dirpath in **/; do
set -- "$dirpath"/*
printf '%s:\t%d\n' "$dirpath" "$#"
done
Note that I only moved one *
from one place to another.
tree -F /SOME/DIR
, where/SOME/DIR
is to be replaced with the actual path (you als might have to installtree
first), would go a long way to have a clear example in the question. – Adaephon Oct 29 '21 at 13:20