Page 1 of 1

Print an array elements based on an input param

Posted: 23 May 2021 13:51
by Newbee
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?

Re: Print an array elements based on an input param

Posted: 23 May 2021 15:01
by aGerman
Use the SET /P trick. It prints a string without new line.

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
Steffen

Re: Print an array elements based on an input param

Posted: 24 May 2021 22:15
by Newbee
Thank you very much aGerman. It works like a charm!
Very nice trick, though. :D