I would like to find the number of folders (recursive, excluding hidden folders) in a given root directory. What command, or series of commands can I use to ascertain this information?
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
-
Thanks. I need this to be recursive; is there a modification that would comply? EDIT: this doesn't seem to omit hidden dirs – jml Nov 11 '14 at 1:48
-
If it is not omitting hidden directories, do you have an
aliasset forlsthat is listing hidden directories by default? – Timothy Martin Nov 11 '14 at 2:05 -
Good point. I had one in my
bash_profile. Thanks for the recursion update as well. – jml Nov 11 '14 at 2:10 -
Be cautious with the -R flag for ls. Check the output without the
wc -lpipe, because I think ls -lR adds blank lines and dir names between files, which might throw off your count. – transistor1 Nov 11 '14 at 18:36 -
2@transistor1 Good point. In this case however the
grep "^d"displays only the entries which have adat the beginning of the line. Blank/non-directory lines should not be displayed without thewc -lor counted with thewc -l. – Timothy Martin Nov 11 '14 at 18:47
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
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.
-
that's interesting - so, there's no built in command to do something like this? – jml Nov 11 '14 at 1:16
-
1@jml - Someone else likely has something simpler, but
findis my go-to for file finding & counting. The "meat" of this ugly expression is really justfind -type d, which finds any directories. – transistor1 Nov 11 '14 at 1:22
Did you try tree command?
tree -d /path/to/maindir| awk END{print}
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.
wcwon't work because it counts files. wouldlswork with a for loop in a bash script or is there something else I'm missing? – jml Nov 11 '14 at 1:03