Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

batch file - DIR output into BAT array?

Is there a way to read in the output of a 'dir' command into an array in a BAT file? Or would I need to output it to a file first, then read the file and delete the file after?

The purpose is to get a list of folders in a directory, append a number to each and then prompt the user for a numerical input to select a folder.

UPDATE : got it!

SETLOCAL EnableDelayedExpansion
SET /A c=1

FOR /F "tokens=*" %%F in ('dir /on /b /a:d /p %svnLOCAL%') DO ( 
    ECHO !c!. %%F
    SET dir_!c!=%%F
    SET /a c=c+1    
)

REM test array
ECHO !dir_4!
ENDLOCAL
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Batch does not formally support arrays, but you can emulate arrays using environment variables.

@echo off
setlocal enableDelayedExpansion

::build "array" of folders
set folderCnt=0
for /f "eol=: delims=" %%F in ('dir /b /ad *') do (
  set /a folderCnt+=1
  set "folder!folderCnt!=%%F"
)

::print menu
for /l %%N in (1 1 %folderCnt%) do echo %%N - !folder%%N!
echo(

:get selection
set selection=
set /p "selection=Enter a folder number: "
echo you picked %selection% - !folder%selection%!

In the code above, the "array" elements are named folder1, folder2, folder3...

Some people use names like folder[1], folder[2], folder[3]... instead. It certainly looks more array like, but that is precisely why I don't do that. People that don't know much about batch see variables like that and assume batch properly supports arrays.

The solution above will not work properly if any of the folder names contain the ! character - the folder name will be corrupted during expansion of the %%F variable because of delayed expansion. There is a work-around involving toggling the delayed expansion on and off, but it is not worth getting into unless it is needed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...