Tuesday, December 1, 2015

Count the Number of Files

We may want to know how many files and subdirectories there are in the current directory. The following is quick solution:
 ls . | wc -l  
Note that the "-l" is an "\ell" not one! This command lists the names of all the files and sub-directories, pipes the list to a tool called wc. Then the wc tool counts the lines of this list, which is the number of the files and sub-directories.

Sometimes, we may want to know the number of files in the sub-directories (of the current directory). This kind of recursive count can be accomplished by
 find . -type f | wc -l  
Here "-type f" restricts the count to be performed on files, not directories.

Similarly, we can do
 find . -type d | wc -l  
to recursively count the directories. But notice that the current directory . is counted in as well. Hence the returned number minus one gives the number of sub-directories.

No comments:

Post a Comment