Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I am trying to define alias for a group of commands counting recursively and displaying the number of all sub-directories encountered for any working directory (including ones with invisible file names). So far what I have done is:

ls -R | wc -l

But it does not display the hidden files number. So I tried this command:

ls -l | grep ^d | wc -l

But I am not sure whether it is the right command or not?

share|improve this question
add comment

3 Answers

up vote 0 down vote accepted

You should never parse the output of ls. See some explanations here:

As others recommended, use find instead. And the best way (even when you have directory names that contain newlines or other types of white space) would be:

alias countdir='find . -type d -print0 | tr -dc "\\0" | wc -c'

See man find, man tr, man wc for more info.

share|improve this answer
add comment

Is find . -type d|wc -l a solution?

share|improve this answer
add comment

I'd recommend using find (man page) to do the searching. As an example,

find . -maxdepth 1 -type d | wc -l

will print the number of all directories in the current working directory.

The -maxdepth option controls how far find will descend into the directories. With a value of 1, it will just use the current directory and list its subdirectories. With 2, it will list the subdirectories' subdirectories, too, and so on.

This has just a single, small drawback: find includes . (the current working directory) in its listing, thus the number returned by wc -l will be off by one.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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