You need a for loop with delayed variable expansion. This will be necessary every time a loop body needs to substitute variables other than that defined by the header.
SETLOCAL ENABLEDELAYEDEXPANSION
for /f %%i in ('dir /b *.pdf') do (set pdf=%%~ni & set str=!pdf:~4,3! & set fname=!pdf:~8! & test.exe !str! !fname!)
I'm not sure why you require to call
the executable but I think you get the idea.
Multiline version:
SETLOCAL ENABLEDELAYEDEXPANSION
for /f %%i in ('dir /b *.pdf') do (
set pdf=%%~ni
set str=!pdf:~4,3!
set fname=!pdf:~8!
test.exe !str! !fname!
)
Now some step by step explanation:
As delayed expansion is off by default we first need to turn it on in line 1. The for loop will run the command in quotes, here dir /b *.pdf
. For each line of output it will set %i
to its value, unroll the loop body by substituting its values and executing it. This is the place where we need the delayed expansion.
Let's say the first line is ABC_100_foo.pdf
, so is the value of %i
. For this line the loop body now looks like this:
set pdf=ABC_100_foo
set str=!pdf:~4,3!
set fname=!pdf:~8!
test.exe !str! !fname!
The expression %%~ni
has been replaced with the file name without extension. The next two statements extract the number 100
and the file name foo
from the variable pdf, and finally the executable is called. Now, for the lines remaining in the output, the loop body will be unrolled and executed again with different values in %i.
Also note that when run in a file you need to put %%i
, when run at the prompt you put %i
.