数组 – 批处理:从动态数组中解析文件路径

参见英文答案 >
Batch recursing through folders & populating an array                                    1个

希望从特定点解析出路径&然后使用它来填充动态数组.

例:

Folder tree:
C:\Main\folder1
C:\Main\folder2\folder2-1
C:\Main\folder3\folder3-1\folder3-2

Desired result:
Array[1]=folder1
Array[2]=folder2
Array[3]=folder2\folder2-1
Array[4]=folder3
Array[5]=folder3\folder3-1\
Array[6]=folder3\folder3-1\folder3-2

这是下面的工作代码返回正常,但在完整路径中:

@echo off
setlocal EnableDelayedExpansion
SET folders=C:\Main

rem Populate the array with existent files in folder
set i=0
for /r "%folders%" /d %%a in (*) do (
   set /A i+=1
   set list[!i!]=%%a
)
set foldnum=%i%

rem Display array elements
for /L %%i in (1,1,%foldnum%) do (SET array[%%i]=!list[%%i]!)

for /F "tokens=2 delims==" %%f in ('set array[') do echo %%f

最佳答案 您将绝对路径传递给FOR循环.但即使使用相对路径,FOR循环也会做太多并将其转换为绝对路径.

这里的技巧是替换FOR循环中的绝对路径.

在实变量中创建循环变量的副本

set AA=%%a

然后在列表“array”中没有任何内容替换前缀反斜杠

set list[!i!]=!AA:%folders%\=!

完整的固定代码:

@echo off
setlocal EnableDelayedExpansion
SET folders=C:\Main

rem Populate the array with existent files in folder
set i=0
for /r "%folders%" /d %%a in (*) do (
   set /A i+=1
   rem create a copy of the loop variable in a real variable
   set AA=%%a
   rem replace prefix+backslash by nothing in a the list "array"
   set list[!i!]=!AA:%folders%\=!
)
set foldnum=%i%

rem Display array elements
for /L %%i in (1,1,%foldnum%) do (SET array[%%i]=!list[%%i]!)

for /F "tokens=2 delims==" %%f in ('set array[') do echo %%f

然后你以相对的方式获得%folders%的所有目录.

点赞