1

I have a problem with .bat

@echo off
    set NAMEFILE=version

rem counting commas
set "f=%VERSION%"
set "vz=,"
set /a "z=0,n=0"
for /f "delims=" %%a in ('findstr /r /c:"\%vz%" "%f%"') do set "s=%%a"& call :#
<+ (for /f "tokens=1,2 delims==" %%b in ('more') do set /a "z+=%%b")& del+

set /a z =%z% + 1

rem cycle with problem
rem tokens=%%a* - part of the code that contains the problem
for /l %%a in (1,1,%z%) do for /f "tokens=%%a* delims=," %%i in (%NAMEFILE%) do @echo %%i>File_%%a.vers


:#
 setlocal enabledelayedexpansion 2>nul
  for %%a in ("!s:~%n%,1!") do (

   if "%%~a"=="%vz%" set /a z+=1
   if not "%%~a"=="" set /a n+=1& goto #
  )
 endlocal
exit /b

I don't know what to do with "tokens=%%a". It doesn't see variable %%a, maybe because of "%" symbols. I think it must be escaped or something like this. If u can help, please help.

  • 1
    It's a bit unclear what you expect and where it fails, it seems that there is much unrelated code. You should try to reduce your code to show a minimal example of your problem and describe what you get and what you expect – jeb Dec 03 '19 at 06:43
  • I have a problem only with following string : `for /l %%a in (1,1,%z%) do for /f "tokens=%%a* delims=," %%i in (%NAMEFILE%) do @echo %%i>File_%%a.vers`. Specifically in this place: `"tokens=%%a* delims=,"`. I need to use "`%%a`" variable in `"tokens=%%a*"`, but I can't do it. It doesn't put this variable in that place. It ignores that. I assume that variable can be escaped somehow, but' I don't know how to do it. – Sergey Krasilnikov Dec 03 '19 at 06:53

1 Answers1

2

You can't use neither delayed expansion nor FOR-parameter expansion in the options part of a FOR command (The same is true for IF).
It's caused by the way the batch parser handles them.

But as said only parameter and delayed expansions fail, percent expansion still works.

But in your sample you can't use it inline, you need to build a helper function.

...
for /l %%a in (1,1,%z%) do call :helper_func %%a
...


:helper_func
for /f "tokens=%1* delims=," %%i in (%NAMEFILE%) do @echo %%i>File_%%a.vers

It looks strange that in the helper function, you still can use %%a in echo %%i>File_%%a.
This is the effect that all currently used FOR-parameters are visible inside all FOR-loops (even when they appear to be unrelated).

jeb
  • 78,592
  • 17
  • 171
  • 225
  • Ok. Thanks. I have tried this code `@echo off set /a z=2 set /a c=0 for /l %%a in (1,1,%z%) do ( set /a c=%c%+1 echo %c% )` And I have gotten following output: "0 0" . Is there a way to increment the variable %c% inside the loop. Why has not it changed? – Sergey Krasilnikov Dec 03 '19 at 07:20
  • 1
    @SergeyKrasilnikov That question is unrelated to your primary question, but have a look at [Why are my set commands resulting in nothing getting stored?](https://stackoverflow.com/q/14347038/463115) – jeb Dec 03 '19 at 07:24