Batch: Parsing out file path from dynamic array [d

2019-05-07 15:22发布

This question already has an answer here:

Looking to parse out the path from a specific point & then use that to populate the dynamic array.

Example:

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

This is the working code below which returns fine but in full paths:

@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

2条回答
放我归山
2楼-- · 2019-05-07 15:51

A little bit of 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
查看更多
乱世女痞
3楼-- · 2019-05-07 16:00

You pass an absolute path to the FOR loop. But even with a relative path the FOR loop does too much and converts it to an absolute path.

The trick here is to replace the absolute path in the FOR loop.

Create a copy of the loop variable in a real variable

set AA=%%a

Then replace prefix+backslash by nothing in the list "array'

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

full fixed code:

@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

then you get all the dirs of %folders% in a relative way.

查看更多
登录 后发表回答