Counting Files and Folders in a Directory
With command line utilities or GUI file explorer, we can count files and folders in a directory on Linux or Windows.
Counting Files and Folders on Linux
To count folders in a directory recursively (excluding the directory itself), we use find
and wc
command:
find "$dirname" -mindepth 1 -type d | wc -l
If you do want to include the directory being counted itself, remove the -mindepth 1
arguments.
If you do not want to count recursively, add -maxdepth 1
.
Similarly, to count files in a directory recursively:
find "$dirname" -mindepth 1 -type f | wc -l
However, these commands will give false readings if file or folder name contains new line characters. To be safe, we should use a null character as the separator and count that:
# Count folders recursively
find "$dirname" -mindepth 1 -type d -print0 | tr -cd '\0' | wc -c
# Count files recursively
find "$dirname" -mindepth 1 -type f -print0 | tr -cd '\0' | wc -c
Counting Files and Folders on Windows
Using File Explorer
The easiest way to count files and folders recursively on Windows is to use File Explorer, and check the folder properties.
Using cmd.exe
To count folders recursively, use:
dir /b /s /ad %dirname% | find /c /v ""
To count files recursively, use:
dir /b /s /a-d %dirname% | find /c /v ""
-
/b
option makesdir
use bare format (no heading information or summary); -
/s
option takes subdirectories into consideration (recursively); -
/ad
option only displays directories (including hidden ones); -
/a-d
option displays all files except directories (including hidden ones); -
find /c /v ""
counts lines, i.e. number of files/folders in this case.
It's safe to use dir
to do the counting even if file/folder names contain new line characters, as new line characters are not output literally by dir
.
Using PowerShell
To count folders recursively, use:
(Get-ChildItem -Recurse -Force -Directory "$dirname").Count
To count files recursively, use:
(Get-ChildItem -Recurse -Force -File "$dirname").Count
-
-Force
reveals hidden and system files/folders; -
-Directory
restricts output to directories; -
-File
restricts output to files.
References
- linux - counting number of directories in a specific directory - Stack Overflow
-
shell script - Count nul delimited items in file - Unix & Linux Stack Exchange
- 4 Ways To Count The Number Of Folders And Files Inside A Folder | Digital Citizen
- powershell - Windows command prompt: how to get the count of all files in current directory? - Server Fault
- Windows PowerShell Tip: Fun Things You Can Do With the Get-ChildItem Cmdlet