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.
There's three problems with your script:
FOR /F
/B
format, ie DIR
outputs more than just filenames 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"
You are very close, but you are missing the switch /B
of the dir
command , so the output contains a header and a footer, which are both included in the count. Therefore, change dir *.txt /s
to dir *.txt /s /b
(same for *.xls
) and the count is going to be correct.
Besides that, there are typos: the closing '
is missing -- for %%x in ('dir *.txt /s') do ...
. In addition, the /F
switch at for
is missing, which is needed to capture the output of a command. (I assume these things are present in the true script as you would receive errors otherwise.)
To count the number of files, you could also do the following:
for /F "delims=" %%X in ('dir /B /S "*.txt" ^| find /C /V ""') do set "COUNT=%%X"
find /V ""
searches for non-empty lines, hence all lines returned by dir /B /S
are considered as matches; the /C
switch simply lets find
return the total amount of matching lines.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.