Home > database >  batch script how to create an array with specific continued numbers
batch script how to create an array with specific continued numbers

Time:01-24

I need to create an integer array that stops at a limit number and then goes on after another fixed value. Something like [1 2 3 4 5 10 11 12 13 14 15 16], where 5 is the limit number and 10 where it restarts.
Can you do something like set arr = [1:%lim%, 10:%max%] ?

CodePudding user response:

@ECHO OFF
SETLOCAL

CALL :buildlist mylist 1 5 10 16

ECHO list is %mylist%

PAUSE

GOTO :eof

:: Produce a list of integers
:: %1 is listname
:: %2 is start value
:: %3 is end-value for range
:: %4 is restart-value
:: %5 is end-value

:buildlist
SET "%1="
FOR /L %%v IN (%2,1,%5) DO (
 IF %%v leq %3 CALL SET "%1=%%%1%% %%v" 
 IF %%v geq %4 CALL SET "%1=%%%1%% %%v"
)

CALL SET "%1=%%%1:~1%%"

GOTO :eof

Batch really doesn't have arrays, but can simulate one with a little imagination.

The above routine produces a list of values to the specification, ready for processing by a for statement.

Although it's possible to use delayedexpansion, it's possible to avoid that facility. By CALL ing a set command, the command is parsed before execution so to decode the hieroglyphics, where %1 is the variable name "var"

SET "%1=%%%1%% %%v"

is processed as:

SET "var=%var% %%v"

as %% is an escaped-%

Similarly,

SET "%1=%%%1:~1%%"

is executed as

SET "var=%var:~1%"

which deletes the first character, which will be a space.

CodePudding user response:

Batch doesn't have OR operators, so you'll have to make do with two separate if statements - one for the first set of numbers and one for the second set of numbers. You can, however, put both of those in the same for loop:

@echo off
setlocal enabledelayedexpansion

set "lim=5"
set "max=10"

REM Setting counter to -1 because we're going to increment the counter and then
REM use it, and arrays famously start at zero.
set "counter=-1"
for /L %%A in (1,1,16) do (
    if %%A LEQ %lim% (
        set /a counter =1
        set "array[!counter!]=%%A"
    )
    if %%A GEQ %max% (
        set /a counter =1
        set "array[!counter!]=%%A"
    )
)

REM Display the contents of the array just to prove it worked.
REM Alphabetic order is used, so array[10] and array[11] are going to print before array[1]
set array[
  •  Tags:  
  • Related