DonG
DonG

Reputation: 821

for loop in batch script increment two or more variables

Yeah, batch scripting. I know. Sorry.

The final goal is to produce a file containing XML elements. Up to now, these items have been created by hand, but there's got to be a better way. My first idea is to do a batch script. What I've been doing up until now is copy/ paste, manually adding +1 to the id, page, and src="page_#" items. It's fine when the xml file contains only 40 entries. Not so fine when we're going past 100 or more.

GOAL: Need to increment the elements, say, navPoint id=#, Page #, and content src=page_# in the below:

<navPoint id="1"><text>Page 1</text><content src="page_1.html"></navPoint>

I've got a working batch script that can loop and update ONE variable, and it is thusly:

echo
for /l %%x in (1, 1, 8) do (
echo ^<navPoint id="navPoint-%%x"^>^<navLabel^>^<text^>Page %%x^</text^>^</navlabel^>^<content src="page_%%x.html"/^>^</navPoint^>)>>C:\Users\me.txt

This last part, >>C:\Users\me.txt, sends it to a txt file.

HOWEVER, I want the Page number to start at 2, not 1. My batch script works great, %%x starts at 1 and increments uniformly. I need another variable in the loop that is one greater than %%x.

so the result would be:

<navPoint id="1"><text>Page 2</text><content src="page_1.html"></navPoint>

and the next result would be:

<navPoint id="2"><text>Page 3</text><content src="page_2.html"></navPoint>

etc...

How can this be accomplished in batch scripting? I thought it would be as simple as %%x+1 but it's not...

Upvotes: 2

Views: 4757

Answers (1)

indiv
indiv

Reputation: 17846

  1. You can do arithmetic with set /a. Do help set from the command line to read about it.

  2. If you set a variable inside a block (e.g., if, for), you need to enable delayed variable expansion with setlocal EnableDelayedExpansion. Then you use ! instead of % to expand the variable. If you are outside of the code block, you can go back to using %. help set also will tell you about delayed expansion.

Using these 2 pieces of information, you can change your code to this to get what you want:

@echo off
setlocal EnableDelayedExpansion
for /l %%x in (1, 1, 8) do (
    set /a PAGENUM=%%x+1
    echo ^<navPoint id="navPoint-%%x"^>^<navLabel^>^<text^>Page !PAGENUM!^</text^>^</navlabel^>^<content src="page_%%x.html"/^>^</navPoint^>
)>>C:\Users\me.txt

Upvotes: 3

Related Questions