Using Variable As For-Loop Token Value
Posted: 03 Jun 2015 11:31
Hello batchers!
I'm trying to split a path string, and I've run into an issue where using %var% as a token value works as expected, but !var! does not:
The resulting output is:
This is a severely reduced version of my script just to show the issue. There are a few other steps that mandate the setting of tokenNum within the loop. Long story short, I never know how deep the file is within the path, so I need to count the number of \ so I can choose the right token value to always return 123458. I can get that number fairly easily, but planting it into a for-loop using exclamation points is breaking the script.
Thank you for your time,
Dave
I'm trying to split a path string, and I've run into an issue where using %var% as a token value works as expected, but !var! does not:
Code: Select all
@echo off
setlocal enableextensions
setlocal enabledelayedexpansion
set "file=E:\temp\TEST\123458--text_text1\filename.mp4"
set tokenNum=4
echo.
for /f "tokens=%tokenNum% delims=\-" %%b in ("%file%") do (
@echo.%tokenNum% = %%b
)
echo.
echo.and now with exclamation points
echo.
for /l %%n in (1,1,5) do (
set "tokenNum=%%n"
for /f "tokens=!tokenNum! delims=\-" %%b in ("%file%") do (
@echo.!tokenNum! = %%b)
)
echo.
pause
The resulting output is:
Code: Select all
C:\Users\davep\Desktop>scratch.bat
4 = 123458
and now with exclamation points
!tokenNum! delims=\-" was unexpected at this time.
!tokenNum! delims=\-" was unexpected at this time.
!tokenNum! delims=\-" was unexpected at this time.
!tokenNum! delims=\-" was unexpected at this time.
!tokenNum! delims=\-" was unexpected at this time.
Press any key to continue . . .
This is a severely reduced version of my script just to show the issue. There are a few other steps that mandate the setting of tokenNum within the loop. Long story short, I never know how deep the file is within the path, so I need to count the number of \ so I can choose the right token value to always return 123458. I can get that number fairly easily, but planting it into a for-loop using exclamation points is breaking the script.
Thank you for your time,
Dave