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.

File Explorer 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 makes dir 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.