How to Count Number of Files and Subdirectories inside a Given Linux Directory?


It often becomes essential to know not just the count of files in my current directory but also the count of files from all the subdirectories inside the current directory. This can be found out using the

Using ls

we can use ls to list the files, then choose only the ones that start with ‘-‘ symbol. The R option along with the l option does a recursive search. The ‘-c’ option counts the number of lines which is the number of files.

ls -lR . | egrep -c '^-'

Running the above code gives us the following result −

13

Using find With Hidden Files

The find command helps us find the files with certain criteria by recursively traversing all the directories and there subdirectories. We use it with the type option to get only files by supplying the argument f. Here it also counts all the hidden files.

find . -type f | wc -l

Running the above code gives us the following result −

1505

Using find Without hidden Files

We use the same approach as in the previous command, but use a regular expression pattern to avoid the . character by using the escape character \.

find . -not -path '*/\.*' -type f | wc -l

Running the above code gives us the following result −

13

Updated on: 03-Jan-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements