for-loopbatch-filevariableslistings

GET THE NUMBER OF FILES WITH A SPECIFIC EXTENSION IN A SPECIFIC FOLDER (BATCH)


I've searched and tryed everything to get the number of file with a specific extension but i did found nothing, so i would need some help please, my problem :

I've got multiple files with differents extensions, and i need to put the number of files that has for extension .NDS in a variable

Ex: (for the exemple, i gonna put 2 files that has the extension .nds)

@echo off
set number=0
FOR %%f in (%CD%\files\*.nds) DO set /a number=%number%+1
echo Nintendo DS : %number% game(s)
pause

Output:

Nintendo DS : 1

but whyyyy, i said that every .nds files that are in %CD%\files found, you set +1 to %number%, and there are 2 files: so why is he giving me 1 and not 2 ? Do someone can give me a solution


Solution

  • You are essentially falling into the delayed expansion trap. But the SET /A command gives you some options to not have to use delayed expansion with the variable.

    Change the set command to one of these option.

    set /a "number=number + 1"
    

    or

    set /a "number+=1"
    

    This explained in the HELP file for the SET command.

    Any non-numeric strings in the expression are treated as environment variable names whose values are converted to numbers before using them. If an environment variable name is specified but is not defined in the current environment, then a value of zero is used. This allows you to do arithmetic with environment variable values without having to type all those % signs to get their values.