Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using batch to count the number of specific files in folder

Tags:

batch-file

I have a bunch of files in a folder that their names are like a1.txt, a6.txt, a8.txt,..and I need to count them I tried this batch file but it does not recognize * as a way to account for all numbers and does not return the correct answer.

set /a count=0
for /F "tokens=* delims= " %%i in ('dir/s/b/a-d "C:\Users\xyz\desktop\Project\a.*"') do (set /a count=count+1) 

Can you see what I am doing wrong? Thanks for your help in advance.

like image 717
user1594078 Avatar asked Sep 07 '25 01:09

user1594078


2 Answers

You could do this in a single line

dir /a-d "C:\Users\xyz\desktop\Project\a.*" | find /C "/"

Explanation:

dir is the directory listing command. The /a starts an attribute filter and the -d tells dir to not list directories. So all files in that directory with a. as the start of the filename are piped to the find command. The find command has a built in /C option to count the lines and lines in this case are files.

like image 127
Okkenator Avatar answered Sep 10 '25 23:09

Okkenator


What you're doing wrong is the wildcard for all files starting with a.

You're using dir a.* and expecting it to find files like a6.txt

Also, to handle filenames with spaces, I suggest you remove the delimiters.

set /a count=0
for /F "delims=" %%i in ('dir/s/b/a-d "C:\Users\xyz\desktop\Project\a*"') do (set /a count=count+1)

( Also listen to the other answers in terms of making your code more efficient. )

like image 31
azhrei Avatar answered Sep 10 '25 23:09

azhrei