
- Operating System Tutorial
- OS - Home
- OS - Overview
- OS - Components
- OS - Types
- OS - Services
- OS - Properties
- OS - Processes
- OS - Process Scheduling
- OS - Scheduling algorithms
- OS - Multi-threading
- OS - Memory Management
- OS - Virtual Memory
- OS - I/O Hardware
- OS - I/O Software
- OS - File System
- OS - Security
- OS - Linux
- OS - Exams Questions with Answers
- OS - Exams Questions with Answers
- Operating System Useful Resources
- OS - Quick Guide
- OS - Useful Resources
- OS - Discussion
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
- Related Articles
- How to grep a string in a directory and all its subdirectories in Linux?
- How to Count Number of Files in Linux
- Get all subdirectories of a given directory in PHP
- How to use the sed command to replace a text in files present in a directory and subdirectories?
- How to get all the files, sub files and their size inside a directory in C#?
- How to unzip all zipped files in a Linux directory?
- How to copy a file, group of files, or directory in Linux?
- Copy Directory Structure Without Files on Linux
- Linux – How to find the files existing in one directory but not in the other directory?
- Diff a Directory for Only Files of a Specific Type on Linux
- Move All Files Including Hidden Files Into Parent Directory in Linux
- Find the Total Size of All Files in a Directory on Linux
- Count the number of rhombi possible inside a rectangle of given size in C++
- How can I iterate over files in a given directory in Python?
- How to copy files into a directory in C#?
