0

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!

1

1 Answer 1

1

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
)
Sign up to request clarification or add additional context in comments.

3 Comments

for "collect first file", the goto is intended to break the loop.
@Stephan yes. I modified goto instead of call. Thanks
@Stephan You are right, I should read the texts more carefully

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.