Count files in a folder and subfolders from the command line
How do I count all files of a given type (eg. *.mp3) in a designated folder (and optionally subfolders) from command line into a environment variable?
(no PowerShell please, just batch commands)
set filesCount=0 & for %f in (*) do @(set /a filesCount+=1 > nul)
Count files in a folder and subfolders
Use the following command:
dir /b *.mp3 /s 2> nul | find "" /v /c > tmp && set /p count=<tmp && del tmp && echo %count%
The environment variable %count%
will contain the number of files.
Note:
- Remove
/s
if you don't want to count files in subfolders.
Example (using *.txt)
Directory listing to show the 17 files:
F:\test>dir /b *.txt /s
F:\test\abc.txt
F:\test\blackwhite.txt
F:\test\cpu.txt
F:\test\interface.txt
F:\test\Lorem ipsum.txt
F:\test\right.txt
F:\test\rights.txt
F:\test\software.txt
F:\test\tabs.txt
F:\test\test.txt
F:\test\this is inside junction.txt
F:\test\unique.txt
F:\test\xyz.txt
F:\test\sub\abc.txt
F:\test\sub\xyz.txt
F:\test\sub with space\junction sub with space.txt
F:\test\sub with space\xyz.txt
Run the command:
F:\test>dir /b *.txt /s 2> nul | find "" /v /c > tmp && set /p count=<tmp && del tmp && echo %count%
17
Further reading
- An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
- find - Search for a text string in a file & display all the lines where it is found.
Use a combination of dir
and find
to count the files. Store the files into a variable via the for
loop. Redirect error output to nul
to hide File Not Found
error.
@echo off
for /f %%i in ('dir *.xlsx /s /b 2^> nul ^| find "" /v /c') do set VAR=%%i
echo %VAR%
See descriptions of parameters using /?
for dir
, find
, and for
.
A little late to the party, but I just wanted to show support for DavidPostill
DIR [LEAVE BLANK FOR ALL FILES, *.mp3, *.*] /B /A-D /S 2>NUL | FIND "" /V /C > tmp
SET /P COUNT=<tmp
SET /A COUNT -= 1
DEL tmp
ECHO !COUNT!
This is my implementation; I prefer to split things up (since the command creates a file, it helps to decrement by one).
NOTE: The above INCLUDES files that are HIDDEN or are SYSTEM files.
To exclude HIDDEN and SYSTEM files replace [DIR...] with this instead
DIR [LEAVE BLANK FOR ALL FILES, *.mp3, *.*] /B /A-D-S-H /S 2>NUL | FIND "" /V /C > tmp
Also, it should be noted that the [dir ...] method is, at least an order of magnitude, more efficient than the [for ... VAR+=1] method.
My case was 510,000 files; using the DIR method, ~6 SECs; using the FOR method, ~4 MINs.