Dir /b output into an Array

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
wbg
Posts: 2
Joined: 06 Mar 2012 10:41

Dir /b output into an Array

#1 Post by wbg » 06 Mar 2012 11:27

Hi All !!

I have looked every where and tried a thousand things but I can not get this to work ... What I want to do is run a DIR /b cammand and display the subdirectories found on the screen with a number (subscript) for future reference / selection - the output should be similar to the following ...
1 firstSubdir
2 scndSubdir
3 anotherSubdir
4 lastSubdir

I have tried using the for loop to display the number and the subdir name but i cannot increment the number - my code

set /a cnt=0
for /f "tokens=*" %%g in ('dir /b') do (
echo '%%g'
set /A cnt=%cnt% + 1
echo cnt=%cnt% )

The output ends up showing the directory name but always 0 for the number
- What am I doing wrong ????

Squashman
Expert
Posts: 4465
Joined: 23 Dec 2011 13:59

Re: Dir /b output into an Array

#2 Post by Squashman » 06 Mar 2012 11:52

Code: Select all

@echo off
setlocal enabledelayedexpansion
set /a cnt=0
for /f "tokens=*" %%g in ('dir /b') do (
   set /A cnt+=1
   echo !cnt! '%%g'
)
endlocal

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Dir /b output into an Array

#3 Post by foxidrive » 06 Mar 2012 12:32

In the MSdos days to create a simple menu, the screen was generated like this:

Code: Select all

dir /ad /b |find /n /v ""

Squashman
Expert
Posts: 4465
Joined: 23 Dec 2011 13:59

Re: Dir /b output into an Array

#4 Post by Squashman » 06 Mar 2012 13:03

foxidrive wrote:In the MSdos days to create a simple menu, the screen was generated like this:

Code: Select all

dir /ad /b |find /n /v ""

Totally forgot about the FIND usage. Thanks foxidrive.

wbg
Posts: 2
Joined: 06 Mar 2012 10:41

Re: Dir /b output into an Array

#5 Post by wbg » 06 Mar 2012 15:22

Awesome !!!

Thank you Squashman & Foxidrive :D

Post Reply