Package: parsing a file path from a dynamic array

We are looking for an analysis of the path from a specific point, and then use it to populate a 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 a fine, but the full path:

@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
+4
source share
2 answers

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

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

Create a copy of the loop variable in the real variable

set AA=%%a

Then replace the prefix + backslash with nothing in the "array" list

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

%folders% .

+2

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
0

Source: https://habr.com/ru/post/1658854/


All Articles