How can I recursively count files in a Linux directory?
To recursively count files in a Linux directory (and its subdirectories), use find along with wc -l. Here’s the most common approach:
find /path/to/directory -type f | wc -l
Explanation:
find /path/to/directory: Searches within the specified directory (recursively by default).-type f: Restricts the search to regular files only (ignoring directories, symlinks, etc.).| wc -l: Pipes the list of found files towc(word count) with-l(line count), giving you the total number of files.
More Tips
-
Counting Specific File Types
For instance, to count only.txtfiles:find /path/to/directory -type f -name "*.txt" | wc -l -
Excluding Certain Directories
If you want to skip folders likenode_modules:find /path/to/directory -type d -name "node_modules" -prune -o -type f -print | wc -lThis command prunes
node_modulesbut counts all other files. -
Potential Edge Cases
- If you have millions of files, the command might be slow or produce a large output buffer before counting.
- Use
-maxdepthor-mindepthif you need to restrict how deep the search goes.
Further Learning
If you’re looking to solidify your scripting, algorithmic, and coding-interview skills, consider these two courses from DesignGurus.io:
-
Grokking Data Structures & Algorithms for Coding Interviews
A thorough exploration of core data structures and algorithmic techniques, crucial for writing efficient code and shell scripts. -
Grokking the Coding Interview: Patterns for Coding Questions
Learn the key coding patterns repeatedly tested in interviews, enabling you to solve problems more systematically and confidently.