0

Im trying to do this rather elementary thing in a DOS batch:

@echo off
set _sets=^
RO:111:Rondonia,^
AC:112:Acre,^
AM:113:Amazonas,^
RR:114:Roraima
set _family_name=MyFamily
FOR %%i IN (%_sets%) DO (
    echo %%i ----- %_family_name%
)

Output:

RO:111:Rondonia -----
AC:112:Acre -----
AM:113:Amazonas -----
RR:114:Roraima -----

After the ----- is supposed to appear "MyFamily", but instead nothing appears.

How do I access variables set outside a FOR loop from within it? I have no idea why the _family_name variable is not visible inside the for loop. I'm somewhat new to batch scripts. I'm used to C++ and Java programming, thus most likely my thinking does not apply to the batch realm.

I also need to split the string triplets "AA:NNN:AAAAAA" into three individual variables. I tried to come up with a nested for loop, but I couldn't tackle this problem.

The example was made simple for clarity. The actual Batch is more complex than that. I have to access 10-12 variables from within the loop. So please consider this aspect before answering. Thanks in advance.

2
  • Your example works here -- I get RO:111:Rondonia ----- MyFamily and so forth. Commented Apr 6, 2014 at 13:48
  • Jim, maybe it was something else in my more complex batch. Your solution with the exclamations solved the puzzle. Thanks. Commented Apr 6, 2014 at 17:54

2 Answers 2

2

If _family_name is actually being set within another (outer) loop, you'll need to enable delayed expansion with something like this:

@echo off
setlocal enabledelayedexpansion

for ...
  set foo=bar
  for ...
    echo !foo!
  )
)

Note that you access the variable with !exclamations! instead of %percents% there.

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

Comments

1

See if this helps you:

FOR /f %%a "tokens=1-4 delims=," IN ("%_sets%") DO (
    echo %%a ----- %_family_name%
    echo %%b ----- %_family_name%
    echo %%c ----- %_family_name%
    echo %%d ----- %_family_name%
)

4 Comments

Those variables created out of thin air (b, c and d) bother me a lot, but the solution worked. Fine, thanks!
The tokens= section can have tokens=1,3,5,6 or tokens=1-10 for 10 tokens. Each token is a segment of the string separated by the characters in the delims= section. The metavariables are sequential from the one used.
Thanks, @foxidrive, for the explanation on the "thin air" (or meta- in your educated speech :) ) variables. Is the sequence an ASCII sequence?
Yes, it is in ASCII sequence.

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.