Is there any command or the group of commands that can count the number of all sub-directories recursively starting with the certain specific letter?
You can use a combination of the
For example, to count the directories starting at the current directory
. and starting with letter 's'
find . -type d -name 's*' -printf "1" | wc -c
-name condition matches against the name of the directory, using shell pattern matching rules (it is also possible to match using regular expression syntax, however that would be overkill here). The
-printf "1" part prints the character
1 each time a match is found, and
wc -c counts these characters.
The choice of
1 as the character printed and counted is arbitrary.
To display and count, you could do
find . -type d -name 's*' | tee >(wc -l)
however be aware that the count may be inaccurate if any directory names include newline characters (rare - but legal).
With python one-liner:
$ tree top top ├── sub1 │ └── another_subdir ├── sub2 └── sub3 4 directories, 0 files $ python -c 'import os,sys;print(sum([ 1 for r,s,f in os.walk(sys.argv) for i in s if i.startswith("s") ]))' ./top 3
The one-liner works as so:
- We're going to pass the directory which we want to traverse as command-line argument, and for that we need
sysmodule, while for directory traversal we need
os.walk()function - hence we need `os module.
print()will print output of
sum()which sums all items inside the list that we create via list comprehension (the
[i for i in iterable]form).
- The list comprehension can be treated as two nested for loops. On each iteration
os.walk()gives top directory, its subdirectories list, and its files list. When we iterate over
ssubdirectories list, we'll check if each subdirectory starts with letter
.startswith()method, and if it does, 1 will be put on to the list. Thus
sum()will basically add up together a long list of 1's.
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.