Count Number of Files and Folders in a Directory Using Terminal

I Googled so much and can’t find any simpler method to count files or folders in a directory in Linux. I am using Ubuntu 14.04. If it’s only files and folders, it would be simple.

Count Files and Folders

$ ls -l | wc -l

The wc -l command is read “WordCount lines”. It means after you executed the ls, the corresponding result will be counted by it’s line. For example, if you are using ls in your working directory, say there are 2 files and 2 folders, it will return 4 lines. If you add it becomes ls -a, it will return 2 more lines. So, it returns 6 lines because of “.” and “..” are counted.

Count Folders Using find

Now, be aware when you want to count files, hidden files, folders, and hidden folders using ls -a command you have to subtract it by 2. It applies almost the same when you try to get the number of folders in a directory. Using find.

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

It will return all folders inside the current directory plus a “.” directory. If you have 2 folders, and 2 hidden folders, the counter will return 5. So, actually your folders just 4.

Count Files Using find

The result of find to count files is exactly the same as the number of actual files including the hidden files in current directory. So, you don’t have to subtract it anymore.

$ find -maxdepth 1 -type f | wc -l

Leave a Reply