Solved Setting a variable in a loop with just one line?

June 20, 2014 at 15:50:33
Specs: Windows 64
If the variable %gmore%=1 and the variable %nm1%=tree, typing "echo %nm1%" will show tree. What I need is to get the same result by being able to type something like
echo nm%gmore% where %gmore%=1.

Here's an example of the current batch code I have:

Contents of dir.txt:

Batch file:
set vid=0
for /F "tokens=*" %%A in (dir.txt) do (
SET /A vid=!vid! + 1
set nm!vid!=%%A
set nm


set /a gmor+=1
if %gmor% == 1 set mor=%nm1% & goto next
if %gmor% == 2 set mor=%nm2% & goto next
if %gmor% == 3 set mor=%nm3% & goto next
if %gmor% == 4 set mor=%nm4% & goto next


echo %mor%
goto start

Instead of typing the above 4 lines in the :start section, I want a method that would be able to do something like this:

set mor=nm%gmor% & goto next

(so that the :start would contain just one line instead of 1000s of lines so that every time the loops goes to the beginning of :start, %mor% gets set as %nm1% if %gmor% is 1, %nm2% if %gmore% is 2,etc. Purpose of wanting to alter the :start code is so that %mor% gets set with just one code of line everytime the loop goes to the beginning and I dont have to type 1000s of lines. Is this possilble? Thank you.

See More: Setting a variable in a loop with just one line?

Report •

June 20, 2014 at 19:05:23
✔ Best Answer

set /a gmor+=1
if not defined nm%gmor% goto :next
echo !nm%gmor%!
set last_one=%gmor%
goto :start
:: more script here?
goto :eof

Report •

June 21, 2014 at 10:44:20
Thank you very much . i had no idea it would be that simple.
It solved the original problem but for some reason when I type:

if %mor% == !nm%gmor%! echo %db1%>>t.txt

it shows up in the batch as:

if %line3% == !nm! echo %tree%>>t.txt

When it should show up as:
if %line3% == %line3% echo %tree%>>t.txt

because %gmor% is 3 and %nm3% is line3 but I need it to type it as
!nm!%gmor% because its in an ongoing one line loop as explained in the first question. For some reason the %gmor% dissapears.

message edited by ssnader

Report •

June 21, 2014 at 12:29:13
All I can think of off hand is maybe %gmor% is assigned inside of a code block (such as a "for" loop or an IF). If you would, post the section of script that's not working.

Report •

Related Solutions

June 21, 2014 at 14:21:43
Actually I just realized that although it shows up in the black dos screen as:

if %line3% == !nm! echo %tree%>>t.txt

the batch is being executed as:

if %line3% == %line3% echo %tree%>>t.txt

So for some reason , the %gmor% in the !nm%gmor%! is not visble in the black dos screen, but it still does what its supposed to, so thankyou very much for your assistance.

message edited by ssnader

Report •

Ask Question