1

I have a batch file which totals the number of directories:

for /d %%a in (*) do set /a count+=1

Now I need to total the directory names ending with the string )x, e.g. Mona Lisa (1986)x

I have tried unsuccessfully with:

for /d %%a in (")x") do set /a count+=1
Compo
  • 30,301
  • 4
  • 20
  • 32
Henrik
  • 23
  • 2

3 Answers3

1

for /d %%d in (*^)x) do set /a count+=1

You may first want to check that it finds them correctly:

for /d %%d in (*^)x) do echo "%%~d"

AlexP
  • 4,160
  • 12
  • 12
  • @Henrik I suggest you also add `setlocal` before the `for` loop to set the variable locally to the script only, the reason is, If you run the file from the same cmd window each time it will I increase the counter each time it is ran as `%count%` is set as an environment variable. by using setlocal, you localise the variable to the script, alternatively, just add `set "count=0"` – Gerhard May 10 '18 at 13:18
  • in the last example, you can simply do `echo %%d` as `%%~d` will strip surrounding quotes which does not exsist and then you are adding quotes as well to the echo anyway.. – Gerhard May 10 '18 at 13:23
  • @AlexP: I have used your " (*^)x) " suggestion with success. And I have not been able to find documentation about the " ^ " Character. Can anybody point me in the direction? – Henrik Jan 27 '19 at 10:09
  • @Henrik: [How does the Windows Command Interpreter (CMD.EXE) parse scripts?](https://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts) – AlexP Jan 27 '19 at 14:01
1

Just an alternative, (the difference being that this doesn't ignore some directories, such as hidden ones):

For /F %%A In ('Dir /AD "*)x" 2^>Nul') Do Set "count=%%A"

You should really precede this with Set "count="

Compo
  • 30,301
  • 4
  • 20
  • 32
1

You can let the find command count the items filtered by the dir command:

dir /B /A:D "*)x" | find /C /V ""

Prepend or append 2> nul to the dir part to suppress error messages in case no such directories exist.

To capture the resulting value and store it in a variable, use a for /F loop:

for /F %%C in ('2^> nul dir /B /A:D "*)x" ^| find /C /V ""') do set "COUNT=%%C"
echo %COUNT%
aschipfl
  • 28,946
  • 10
  • 45
  • 77