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
A little bit of Tom Foolery.
You pass an absolute path to the
FOR
loop. But even with a relative path theFOR
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
Then replace prefix+backslash by nothing in the list "array'
full fixed code:
then you get all the dirs of
%folders%
in a relative way.