nawazlj
nawazlj

Reputation: 821

Windows batch: Reset Variable

I am trying to collect first file from the directory then process the file. But at the second time when the running and processing the batch file I am unable to store the values in the variable for the file name

Below is the sample code:

for /R C:\abcde_efghij\ab_abcabca %%i IN (*.*) DO (
set filename=%%i
 set newname=%filename:~14%
 set transname=%filename:~25%
goto tests
)
:tests
echo %filename%
echo %newname%
echo %transname%

I am sure we have to use something called SETLOCAL but I am unable to make it in the above code.

Any Help!

Upvotes: 0

Views: 4409

Answers (1)

jeb
jeb

Reputation: 82237

You should avoid percent expansion inside of blocks, also FOR blocks, as the expansion only occours only once when the block is parsed.

for /R C:\abcde_efghij\ab_abcabca %%i IN (*.*) DO (
 set filename=%%i
 goto :tests   # Get only the first file
)
exit /b

:tests
set newname=%filename:~14%
set transname=%filename:~25%
echo %filename%
echo %newname%
echo %transname%
exit /b

As @Stephan noted, you could also use delayed expansion inside blocks.

setlocal EnableDelayedExpansion
for /R C:\abcde_efghij\ab_abcabca %%i IN (*.*) DO (
  set filename=%%i
  set newname=!filename:~14!
  set transname=!filename:~25!

  goto :tests   # Get only the first file
)

Upvotes: 1

Related Questions