Search code examples
windowsbatch-filecmd

Error when setting variable as a result of other variables and numbers in a loop


In the script below where I count filetypes and then perform a ffmpeg on all those files I try to echo a progress of sorts but when setting the pprog:

@echo on & setlocal

set count=0
set pattern=*.mp4
set pattern0=*.webm
for /f %%i in ('dir /b /a-d %pattern% ^| find /c /v ""') do @call set count=%%i
for /f %%i in ('dir /b /a-d %pattern0% ^| find /c /v ""') do @call set count0=%%i
set sum=%count% + %count0%
set total=%sum%
FOR /r %%i in (*.mp4,*.webm) DO (
set /A pprog=((100-%sum%)*100) / (%count%+%count0%)
set /A sum=%sum% - 1
echo %pprog% done %sum% files left out of %total%
)
pause

I get this error:

*100 is unexpected at this time.

I understand that anything after the first closing parentheses is not properly recognized and it throws the next thing after it as "X" was unexpected. The result from set /A pprog=((100-%sum%)*100) / (%count%+%count0%) should be a normal number,the calcualtion is wrong ignore it , it doesnt change the issue, the whole output is this:

E:\Desktop\New folder>test2.bat
E:\Desktop\New folder>set count=0
E:\Desktop\New folder>set pattern=*.mp4
E:\Desktop\New folder>set pattern0=*.webm
E:\Desktop\New folder>for /F %i in ('dir /b /a-d *.mp4 | find /c /v ""') do @call set count=%i
File Not Found
E:\Desktop\New folder>for /F %i in ('dir /b /a-d *.webm | find /c /v ""') do @call set count0=%i
E:\Desktop\New folder>set sum=0 + 10
E:\Desktop\New folder>set total=0 + 10
*100) was unexpected at this time.
E:\Desktop\New folder>set /A pprog=((100-0 + 10)*100) / (0+10)
E:\Desktop\New folder>

The file not found is not an issue. Just use the numbers here if you want to experiment. Edited to remove rem lines and rerun the script and updated the output. Edited to add more explanation to the error.


Solution

  • As mentioned in the comments, there are a few issues with your code (both syntax-wise and logical). Here is a revised version:

    @echo off & setlocal enabledelayedexpansion
    set "count=0"
    set "pattern=*.mp4"
    set "pattern0=*.webm"
    for /f %%i in ('dir /b /s  /a-d "%pattern%" "%pattern0%" ^| find /c /v ""') do set "total=%%i"
    set "counter=0"
    FOR /r %%i in ("%pattern%","%pattern0%") DO (
      set /A count+=1
      set /A pprog=count*100/total
      echo !pprog!%% - !count! files of %total% done. (%%i)
    )