0

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?

4

You can use a combination of the find and wc commands

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

The -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).

  • what does -name actually does ?? and what does -printf "1" does in this case ?? – Abiral Dec 8 '15 at 16:50
  • @Abiral please see updated answer – steeldriver Dec 8 '15 at 18:48
0

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[1]) 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 sys module, 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 s subdirectories list, we'll check if each subdirectory starts with letter s , via .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.
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.