简体   繁体   中英

batch script to add number to a string in loop

i need to generate list of dummy users. no of users will be provided as a input.. like 5 or 500 or 5000. all i want is to have a standard text like usr and append a number and generate the list like usr1, usr2, usr3 etc. I thought i can do this in batch file quickly. but stuck with loop and appending the number to the string.. can some help?

@echo  OFF  
SETLOCAL ENABLEDELAYEDEXPANSION
set /p numb="Enter how many users to be generated "
set numb2=0
set x=0
set name1=tstusr
set name1=tstusr
set name2=%name1%
for /l %%x in (1,1,%numb%) do (
echo %%x
set numb2=%%x
set name1=tstusr
set name2=%name1%%numb2%
echo %name1%
echo %name2%
)

I'm not sure if I'm getting it right. You want simply a script which asks you for a number X and then outputs

usr1

usr2

usr3

...

usrX

In this case this would be the code:

@ECHO  OFF  
SET /p numb="Enter how many users to be generated "
FOR /l %%I IN (1,1,%numb%) DO (
    ECHO usr%%I
)
PAUSE

If that's not the question, plz help me understanding your script. Eg why do you use set name1=tstusr three times?

with a slight modification of your code...

@echo  OFF  
SETLOCAL ENABLEDELAYEDEXPANSION
set /p numb="Enter how many users to be generated "
set numb2=0
set x=0
set name1=tstusr
set name1=tstusr
set name2=%name1%

for /l %%x in (1,1,%numb%) do (
    echo %%x
    set numb2=%%x
    set name1=tstusr
    set name2=!name1!!numb2!
    echo !name1!
    echo !name2!
)

endlocal
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
set /p numb="Enter how many users to be generated "
>q28342811.txt ECHO tstusr%random%
:loop
set "name=tstusr%random%"
FINDSTR /x "%name%" q28342811.txt >NUL
IF ERRORLEVEL 1 SET /a numb -=1&>>q28342811.txt ECHO %name%
IF %numb% gtr 1 GOTO loop 

TYPE q28342811.txt

GOTO :EOF

Produces q28342811.txt

generate a random username to the output file, then repeat the operation numb -1 times, checking that the new candidate doesn't already exist in the file first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM