Is there a way to print an array elements based on an input param, let's say 100, all in one line.
To simplify the question, I have the following batch file and it will print 3 elements in one line.
@echo off
setlocal enabledelayedexpansion
set w[0]=1
set w[1]=2
set w[2]=3
set w[3]=4
set w[4]=5
call :printArray 3
exit /b
:printArray %1
if %1 equ 1 echo !w[0]!
if %1 equ 2 echo !w[0]! !w[1]!
if %1 equ 3 echo !w[0]! !w[1]! !w[2]!
if %1 equ 4 echo !w[0]! !w[1]! !w[2]! !w[3]!
if %1 equ 5 echo !w[0]! !w[1]! !w[2]! !w[3]! !w[4]!
What if I have a bigger array and I want to print up to 100 elements?
I could modify the :printArray function to do like the above but it really tedious and time consuming.
Is there anyway to make it auto generate the number of elements that I would like to print based on input number?
Print an array elements based on an input param
Moderator: DosItHelp
Re: Print an array elements based on an input param
Use the SET /P trick. It prints a string without new line.
Steffen
Code: Select all
@echo off
setlocal enabledelayedexpansion
set w[0]=1
set w[1]=2
set w[2]=3
set w[3]=4
set w[4]=5
call :printArray 3
pause
exit /b
:printArray %1
set /a "n=%1-1"
for /l %%i in (0 1 %n%) do <nul set /p "=!w[%%i]! "
echo(
exit /b
Re: Print an array elements based on an input param
Thank you very much aGerman. It works like a charm!
Very nice trick, though.
Very nice trick, though.