通过文件夹和文件夹批量递归填充数组 [英] Batch recursing through folders & populating an array
问题描述
我正在寻找通过文件夹/子文件夹/等进行递归的方法. &动态地使用文件夹路径填充数组.
I am looking to recurse through folders/subfolders/etc. & populate an array with the folder paths dynamically.
示例:我有一个名为"A"的文件夹,该文件夹有2个子文件夹"B"& C". "C"有一个子文件夹"D".这样的数组将是:
Example: I have a folder called "A" which has 2 subfolders "B" & "C". "C" has a sub folder "D". So the array would be:
Folder[01]=A
Folder[02]=A/B
Folder[03]=A/C
Folder[04]=A/C/D
FOR/D命令可以满足我的需要吗?如果是这样,我该如何处理循环得到的结果?将其添加到数组?不幸的是必须分批进行.谢谢!
Would FOR/ D command work with what I need? If so, how do I take what the loop gets & add it to an array? Has to be in batch unfortunately. Thank you!
推荐答案
如何动态地使用文件夹路径填充数组.
使用以下批处理文件(MakeFolderArray.cmd):
How do I populate an array with the folder paths dynamically.
Use the following batch file (MakeFolderArray.cmd):
@echo off
setlocal enabledelayedexpansion
rem get length of %cd% (the current directory)
call :strlen cd _length
set /a _index=1
for /d /r %%a in (*) do (
set _name=%%a
rem remove everything from the drive root up to the current directory,
rem which is _length chars
call set _name=!!_name:~%_length%!!
rem replace \ with /
set _name=!_name:\=/!
set Folder[0!_index!]=!_name!
set /a _index+=1
)
set /a _index-=1
for /l %%i in (1,1,%_index%) do (
echo Folder[0%%i]=!Folder[0%%i]!
)
endlocal
goto :eof
:strLen strVar [rtnVar]
setlocal disableDelayedExpansion
set len=0
if defined %~1 for /f "delims=:" %%N in (
'"(cmd /v:on /c echo(!%~1!&echo()|findstr /o ^^"'
) do set /a "len=%%N-3"
endlocal & if "%~2" neq "" (set %~2=%len%) else echo %len%
exit /b
示例:
F:\test>MakeFolderArray
Folder[01]=/A
Folder[02]=/A/B
Folder[03]=/A/C
Folder[04]=/A/C/D
积分:
感谢 dbenham 从
Thanks to dbenham for the strlen
code from this answer (which works if the string contains \
characters).
- Windows CMD命令行的AZ索引-与Windows cmd行相关的所有内容的绝佳参考.
- dir -显示文件和子文件夹的列表.
- 对于/l -有条件地执行一系列数字的命令.
- 用于/d -有条件地对多个目录/文件夹执行命令.
- 设置-显示,设置或删除CMD环境变量.使用SET所做的更改将仅在当前CMD会话期间保持不变.
- 变量编辑/替换-编辑并替换分配给字符串变量的字符.
- 变量-提取部分变量(子字符串).
- An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
- dir - Display a list of files and subfolders.
- for /l - Conditionally perform a command for a range of numbers.
- for /d - Conditionally perform a command on several Directories/Folders.
- set - Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.
- variable edit/replace - Edit and replace the characters assigned to a string variable.
- variables - Extract part of a variable (substring).
这篇关于通过文件夹和文件夹批量递归填充数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!