Ubuntu: Confused with the alias solution?



Question:

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?


Solution:1

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.


Solution:2

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


Solution:3

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »