DIR 输出到 BAT 阵列? [英] DIR output into BAT array?
问题描述
有没有办法将dir"命令的输出读入 BAT 文件中的数组?还是需要先输出到文件,然后读取文件再删除?
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.
更新:知道了!
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
推荐答案
Batch 不正式支持数组,但您可以使用环境变量模拟数组.
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%!
在上面的代码中,数组"元素被命名为folder1、folder2、folder3...
In the code above, the "array" elements are named folder1, folder2, folder3...
有些人使用文件夹[1]、文件夹[2]、文件夹[3]...之类的名称.它当然看起来更像数组,但这正是我不这样做的原因.不太了解批处理的人看到这样的变量并假设批处理正确支持数组.
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.
如果任何文件夹名称包含 !
字符,则上述解决方案将无法正常工作 - 由于延迟扩展,文件夹名称将在 %%F 变量的扩展期间损坏.有一个解决方法,包括打开和关闭延迟扩展,但除非需要,否则不值得进入.
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.
这篇关于DIR 输出到 BAT 阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!