views:

117

answers:

1

I need to randomly generate a number of values in a batch file that share a certain range and concatenate them together separated by spaces. Everything works except for concatenating the space-separated numbers together. The specific problematic issue is concatenating with the numbers with spaces, how do I go about this?

The relevent portion follows:

::Assume %minA%, %maxA% and %randB% are defined correctly.
set /a randA=(%random% %% %maxA%) + %minA%
set agent_counter=0
:start_agent_loop
if %agent_counter% equ %randA% goto end
set /a randApos=(%random% %% %randB%) + 1
::supposedly (if I recall), simply having a space between %agent_starts%
::and %randApos% should do the trick, this doesn't seem to be the case.
set agent_starts = %agent_starts% %randApos%
set /a agent_counter +=1
goto start_agent_loop

:end
echo -A %agent_starts%

Ideally, this should print something like...

C:\Path\>genparams.bat
-A 2 4 5

Currently I get

-A
+2  A: 

The following website (SS64.com) is INVALUABLE for batch script reference. There are excellent pages on SET, IF, you name it.

The SET command is not very forgiving with extra whitespace. Also, set /a will apparently check all strings to see if they are a variable, so I don't think the %'s are required around maxA and minA. I assumed %random% was a special batch file variable that returns a random number, so I did not remove them from that. (though you might be able to)

Change:

set /a randA=(%random% %% %maxA%) + %minA%

To:

set /a randA=(%random%%%maxA)+minA

And change:

set agent_starts = %agent_starts% %randApos%

To:

set agent_starts=%agent_starts% %randApos%

Doing that (and setting a minA=1,maxA=10,randB=5), I got this on my first run: "-A 3 4 3".

Joshua McKinnon
Thanks for your quick reply! Indeed, all I needed to do was remove the spaces such that it looks like your fourth line of script and it worked like a charm!
Geoff
Also, I modified the file with your first recommendation (removing superfluous % signs) and it continued to work, but now it looks cleaner. :) As you guessed, I did have to keep them for %random%.
Geoff
Sweet - glad to help. I was dealing with a separate "spaces" type issue in a batch script today, so I felt your pain :)
Joshua McKinnon