Print an array elements based on an input param

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Newbee
Posts: 9
Joined: 12 Jun 2018 13:50

Print an array elements based on an input param

#1 Post by Newbee » 23 May 2021 13:51

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?

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Print an array elements based on an input param

#2 Post by aGerman » 23 May 2021 15:01

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

Newbee
Posts: 9
Joined: 12 Jun 2018 13:50

Re: Print an array elements based on an input param

#3 Post by Newbee » 24 May 2021 22:15

Thank you very much aGerman. It works like a charm!
Very nice trick, though. :D

Post Reply