希望从特定点解析出路径&然后使用它来填充动态数组。
示例:
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
答案 0 :(得分:2)
您将绝对路径传递给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%
的所有目录。
答案 1 :(得分:0)
Tom Foolery的一点点。
@echo off
setlocal EnableDelayedExpansion
SET folders=C:\Main
subst B: %folders%
B:
set i=0
for /r /d %%G in (*) do (
set /A i+=1
FOR /F "tokens=* delims=\" %%H IN ("%%~pnG") do set "array[!i!]=%%~H"
)
C:
subst B: /D
set foldnum=%i%
rem Display array elements
for /F "tokens=2 delims==" %%f in ('set array[') do echo %%f
pause