Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch file that counts the number of files in EVERY folder in a directory, and outputs results to a text file

What I'm trying to do is make a batch file that'll recursively go into every folder and count the number of files in each folder. However, I've spent the last hour trying various things and it isn't working.

I want the output to look like: X:Y where X is the folder name and Y is the # of files in X.

setlocal EnableDelayedExpansion
set current=blank
FOR /D %%G in ("*") DO set current=%%G && call:count

:count
set count=0
for %%A in (*) do set /a count+=1
echo !current!:!count!>>"D:\User\Some\Directory\count.txt"

But this doesn't work. The output is giving the same number for each folder. The number it's outputting is the number of files in the directory itself, which I think is the problem.

Specifically, if I'm in C:\User\Example and it has three folders, A, B, and C, I want the number of files in C:\User\Example\A and so on, but it's giving me the number of files in C:\User\Example. Hope that makes sense.

Note: In my use case, the folders will not contain sub-directories.

like image 975
Ambushes Avatar asked Jan 05 '23 14:01

Ambushes


2 Answers

A little different approach.

 @echo off

 FOR /D %%G in ("*") DO (
     PUSHD "%%G"
     FOR /F "delims=" %%H in ('dir /a-d /b * ^|find /C /V ""') DO echo %%G %%H>>"..\count.txt"
     POPD
 )
like image 187
Squashman Avatar answered May 10 '23 13:05

Squashman


this works:

note that you have to collate set current=%%G&& call:count or current value is "A " (trailing space, not that you want) And when you scan the subdir, you have to prefix * by your current dir

@echo off
del count.txt

setlocal EnableDelayedExpansion
set current=blank


FOR /D %%G in ("*") DO set current=%%G&& call:count

goto end

:count
set count=0
for %%A in (!current!\*) do set /a count+=1
echo !current!:!count!>>"count.txt"

:end
like image 39
Jean-François Fabre Avatar answered May 10 '23 14:05

Jean-François Fabre