且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何基于指定的文件夹路径获取目录树中每个文件的相对路径?

更新时间:2023-01-04 12:46:09

我不确定您要完成什么,但这至少会为您提供一个良好的起点:

I'm not sure what you want to accomplish, but at least this will give you a good starting point:

@echo off & setlocal enabledelayedexpansion

set rootdir=D:\download

for /R %rootdir% %%F in (*) do (
    set "B=%%~pF"
    set "B=!B:~10!"
    echo Full   : %%F
    echo Partial: !B!
    echo(
)

endlocal

由于要在循环中修改变量,因此需要告诉命令解释器您要允许变量延迟扩展".这就是 setlocal enabledelayedexpansion 的目的.然后,您可以使用作为变量定界符,而不是,这样编写的变量将在运行时扩展.这是必需的,因为 for 循环将像被调用一样被调用.(当您省去 echo 时,您会看到此信息.)

Since you're modifying a variable within a loop, you need to tell the command interpreter that you want to allow variables to be "expanded with delay". This is what the setlocal enabledelayedexpansion is for. Then you can use ! as a variable delimiter instead of %, and variables written as such will be expanded at runtime. This is necessary because the for loop will be called like it is one single call. (You can see this when you leave out the echo off.)

编辑:修改后的示例,其中包括自动切断功能:

Edit: Revised example which includes automatic cut off:

@echo off
setlocal enableextensions enabledelayedexpansion

set "rootdir=%~f1"
if not defined rootdir set "rootdir=%CD%"
set "rootdir=%rootdir:/=\%"
if "%rootdir:~-1%" == "\" set "rootdir=%rootdir:~0,-1%"
set "foo=%rootdir%"
set cut=
:loop
if defined foo (
    set /A cut+=1
    set "foo=!foo:~1!"
    goto :loop
)
echo Root dir: %rootdir%
echo strlen  : %cut%

rem also remove leading /
set /A cut+=1

for /R "%rootdir%" %%F in (*) do (
    set "B=%%~fF"
    rem take substring of the path
    set "B=!B:~%cut%!"
    echo Full    : %%F
    echo Partial : !B!
    echo(
)
endlocal