批处理:从动态数组中解析出文件路径 [英] Batch: Parsing out file path from dynamic array
问题描述
试图从特定点解析路径&然后使用它来填充动态数组.
Looking to parse out the path from a specific point & then use that to populate the dynamic array.
示例:
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
推荐答案
您将绝对路径传递到FOR
循环.但是即使使用相对路径,FOR
循环也会执行过多操作,并将其转换为绝对路径.
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.
这里的技巧是替换FOR
循环中的绝对路径.
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
然后用"array"列表中的所有内容替换前缀+反斜杠
Then replace prefix+backslash by nothing in the list "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%
的所有目录.
then you get all the dirs of %folders%
in a relative way.
这篇关于批处理:从动态数组中解析出文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!