How can I count the number of folders in a drive using Linux?
Navigate to your drive (Can open a terminal window there) and simply execute:
ls -lR | grep ^d | wc -l
-
Find all folders in total, including subdirectories:
find /mount/point -type d | wc -l
-
Find all folders in the root directory (not including subdirectories):
find /mount/point -maxdepth 1 -mindepth 1 -type d | wc -l
The
-maxdepth 1
confines the command to the current directory (i.e., it forbids recursion); the-mindepth 1
causes it not to include the top-level directory (the mount point) itself.
Newlines are valid characters in directory names. I suggest letting find
print a character for each directory found and then letting wc
count those characters:
find /mount/point -mindepth 1 -type d -printf 'a' | wc -c
Specify -mindepth 1
to avoid counting the mount point directory itself.
Try the following [but see below]:
ls -1 -Ap /mount/point | grep "/" | wc -l
Note: the first option to ls
is dash one,
but the option to wc
is dash lower case L.
This will print a one-column list of the current directory
(including .
entries other than .
and ..
themselves),
with trailing slashes for items that are subdirectories,
then count the lines with the slashes.
If you want to look at the entire directory tree (i.e., look at the directory recursively), you should probably go with quack quixote's answer, as it is a little more explicit, but I've corrected mine (after taking quack's suggestions into account):
ls -ARp /mount/point | grep '/$' | wc -l
I have written ffcnt
to speed up recursive file counting under specific circumstances: rotational disks and filesystems that support extent mapping.
It can be an order of magnitude faster than than ls
or find
based approaches.