1

Below is my script. I am trying to look into folders one level below and pick out only those folders, hence the ~-9 which extracts the last 9 chars from the path. But the set var= does not unset the variable because the output comes back with the same folder name repeated # times. Also batch doesn't allow me to do this extract trick directly on %%i, hence the need for the local variable.

How do I clear this variable so that it takes the new value in the next iteration?

@echo off
 for /d %%i in (%1\*) do (
  set var=%%i
  echo %var:~-9%
   set "var="
)
0

2 Answers 2

2

http://judago.webs.com/variablecatches.htm has an explanation for my problem. The magic lines were setlocal enabledelayedexpansion and calling var as echo !var:~-9!. ! vs % ...wow! cmd still amazes me.

Sign up to request clarification or add additional context in comments.

1 Comment

+1, good job finding the source of your problem. You still have a potential problem if names contain !.
0

You found the source of your problem, as well as the solution - delayed expansion.

But using FOR while delayed expansion is enabled can cause problems if any of the filenames contain the ! character. The expansion of the for variable %%i will be corrupted if the value contains ! and delayed expansion is enabled. This is not a frequent problem, but it happens.

The solution is to toggle delayed expansion on and off within the loop

@echo off
setlocal disableDelayedExpansion
for /d %%i in (%1\*) do (
  set var=%%i
  setlocal enableDelayedExpansion
  echo !var:~-9!
  endlocal
)

I'm also wondering what you mean by "I am trying to look into folders one level below and pick out only those folders, hence the ~-9 which extracts the last 9 chars from the path". I suspect your are trying to get the name of the child folder, without the leading path information. If that is so, then using the substring operation is not a good solution because the length of folder names varies.

There is a very simple method to get the name of the folder without the leading path info:

for /d %%i in (%1\*) do echo %%~nxi

Comments

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.