Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch file to count file types in sub directories

I need a batch file that counts certain file types in sub directories. In this case it's .txt and .xls files. At the end of the file it reports this back.

@echo off
REM get script directory
set scriptdir=%~dp0
REM change directory to script directory
cd /d %scriptdir%
setlocal
set txtcount=0
set xlscount=0
for %%x in ('dir *.txt /s ) do set /a txtcount+=1
for %%x in ('dir *.xls /s ) do set /a xlscount+=1
echo %txtcount% text files
echo %xlscount% .xls files
endlocal
pause

My batch file doesn't report back the correct count of files. I thought it might be continually counting but I've set the count variables to local so I'm not sure what's up.

like image 803
Mr Mystery Guest Avatar asked Sep 05 '25 03:09

Mr Mystery Guest


1 Answers

There's three problems with your script:

  • You want to iterate over command output, so you need FOR /F
  • You're not using the "bare" /B format, i.e. DIR outputs more than just filenames
  • You're missing the closing single quote twice

Replace your loops with this:

FOR /F %%X IN ('DIR /S /B *.txt') DO SET /A "txtcount+=1"
FOR /F %%X IN ('DIR /S /B *.xls') DO SET /A "xlscount+=1"
like image 181
zb226 Avatar answered Sep 07 '25 20:09

zb226