I would like to print the number of folders (recursive, excluding hidden folders) in a given CWD / current directory. What command, or series of commands can I use to ascertain this information?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
This will find the number of non-hidden directories in the current working directory:
ls -l | grep "^d" | wc -l
EDIT:
To make this recursive, use the -R option to ls -l:
ls -lR | grep "^d" | wc -l
Method 2
In the GNU land:
find . -mindepth 1 -maxdepth 1 -type d -printf . | wc -c
elsewhere
find . -type d ! -name . -printf . -prune | wc -c
In bash:
shopt -s dotglob count=0 for dir in *; do test -d "$dir" || continue test . = "$dir" && continue test .. = "$dir" && continue ((count++)) done echo $count
Method 3
echo $(($(find -type d | wc -l) - 1)) is one way (subtract 1 from the wc -l to remove the current dir). You can tweak the options to find to find different things.
echo $(($(find -type d -not -path '*/.*' | wc -l) - 1)) – to exclude the hidden dirs
As I mentioned in the comments, the heart of this expression is really find -type d, which finds all directories.
Note this finds all subfolders as well – you can control the depth using the -maxdepth flag.
Method 4
Did you try tree command?
tree -d /path/to/maindir| awk END{print}
Method 5
In zsh:
(){echo $#} *(N/)
Recursively:
(){echo $#} **/*(N/)
Add the D glob qualifiers if you also want to count hidden directories.
POSIX equivalents:
ls -p | grep -c /
(add the -A option to ls for hidden ones)
Recursively:
LC_ALL=C find .//. ! -name . ( -name '.*' -prune -o -type d -print ) | grep -c //
Or
LC_ALL=C ls -Rqn . | grep -c '^d'
To include hidden ones:
LC_ALL=C find .//. ! -name . -type d | grep -c //
or:
LC_ALL=C ls -ARqn . | grep -c '^d'
Method 6
find . -type d -not -path '.' -printf 0 | wc -c ;
Recursively find all directories (-type d) within current directory (find .) that is not (.) directory and print 0 for each directory found. Then wc -c counts the number of characters (0) from the previous command output.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0