0

I would like to write a FOR loop in a batch file to create some variables.

I'm setting up variables in a menu that has 60 options. Variables item1 to item60 contain menu items some of which are empty. The variable %pad% contains 40 spaces. So the following code ensures that each menu item dis1 to dis60 is 40 characters long.

set dis1=%item1%%pad%
set dis1=%dis1:~0,40%

So the problem is I need to repeat this code 60 times as follows:

set dis1=%item1%%pad%
set dis1=%dis1:~0,40%

To...

set dis60=%item60%%pad%
set dis60=%dis60:~0,40%

Please could you tell me a FOR loop to accomplish this task. I'm not sure how to increment the 1-60 value since it's inside a variable.

Compo
  • 36,585
  • 5
  • 27
  • 39
Robin
  • 3
  • 2
  • 2
    Open a Command Prompt window, type `for /?`, and press the `[ENTER]` key. The information you need should form part of the output. Please read it, instead of expecting us to waste our weekend, so you don't have to. BTW, you cannot have an empty variable! You will probably need to also look up delaying variable expansion too. – Compo Jul 29 '23 at 23:41

1 Answers1

0
@ECHO OFF
SETLOCAL enabledelayedexpansion
FOR /L %%e IN (1,1,12) DO SET "dis%%e=item %%e"
SET "pad=           wxyz"
FOR /L %%e IN (1,1,12) DO (
 SET "dis%%e=!dis%%e!%pad%"
 SET "dis%%e=!dis%%e:~0,20!"
)
FOR /L %%e IN (1,1,12) DO ECHO !dis%%e!

ENDLOCAL

SETLOCAL
FOR /L %%e IN (1,1,12) DO SET "dis%%e=item %%e"
SET "pad=           wxyz"
FOR /L %%e IN (1,1,12) DO CALL :padme dis%%e
FOR /L %%e IN (1,1,12) DO CALL ECHO %%dis%%e%%

GOTO :EOF

:padme
CALL SET "%1=%%%1%%%pad%"
CALL SET "%1=%%%1:~0,20%%"

GOTO :eof

Here's two methods, one using delayedexpansion and the other with delayedexpansion disabled (default condition) Stephan's DELAYEDEXPANSION link

I added a few characters to the end of the pad variable to show that the added characters are properly truncated. Obviously, the number should be changed to suit your situation. The demo ones I used are for a manageable output.

Magoo
  • 77,302
  • 8
  • 62
  • 84