DIR输出到BAT阵列? [英] DIR output into BAT array?

查看:199
本文介绍了DIR输出到BAT阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在一个dir命令的输出读入一个BAT文件的数组?或者,我需要它输出到一个文件,然后再读取文件后删除文件?

的目的是为了获得一个文件夹列表中的一个目录,一个号码追加到每然后提示用户为一个数字输入以选择一个文件夹。

更新:!知道了

  SETLOCAL EnableDelayedExpansion
SET / A C = 1FOR / F令牌= *%% f由于('DIR / ON / B / A:D / P%svnLOCAL%')DO(
    ECHO!c请! %%F
    SET dir_!!C = %%˚F
    SET / A C = C + 1
)REM测试阵列
ECHO!dir_4!
ENDLOCAL


解决方案

批次没有正式支持数组,但你可以使用环境变量模拟数组。

 关闭@echo
SETLOCAL enableDelayedExpansion文件夹::打造阵
设置fold​​erCnt = 0
FOR / FEOL =:delims =%% f由于('DIR / B /广告*')做(
  集/ A folderCnt + = 1
  设置文件夹!folderCnt!= %% F
)::打印菜单
对/ L %% N的(11%folderCnt%)做回声%% N - !文件夹%% N!
回声(:GET选择
集选择=
集/ P选择=输入一个文件夹编号:
呼应你挑%选择% - 文件夹%选择%!

在上面的code,在数组的元素被命名文件夹1,文件夹2,folder3 ...

有人使用类似的文件夹[1],文件夹[2],文件夹名称[3] ...来代替。这当然看起来更像数组,但毕竟是precisely我为什么不这样做。不知道批许多人看到这样的变量和假设批量正确支持数组。

上述解决方案将无法正常工作,如果任何一个文件夹名称包含 字符 - 文件夹名称将%%˚F变量的扩张过程中受到破坏的延迟扩展。有一个工作围绕涉及切换和关闭延迟扩展,但它是不值得进入,除非它是需要的。

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

解决方案

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.

这篇关于DIR输出到BAT阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆