如何基于指定的文件夹路径获取目录树中每个文件的相对路径? [英] How to get the relative path for each file in a directory tree based on specified folder path?

查看:50
本文介绍了如何基于指定的文件夹路径获取目录树中每个文件的相对路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想递归地遍历目录,并获得具有完整文件路径以及相对于基本文件夹路径的路径的文件名.例如,位于 D:\ foo \ bar \ a \ b \ file.txt 中的文件具有相对路径 bar \ a \ b \ .

I want to loop recursively through a directory and get the file names with full file path and additionally with path relative to the base folder path. For example, a file located in D:\foo\bar\a\b\file.txt has the relative path bar\a\b\.

我现在正在使用此代码,该代码无法按预期工作:

I'm using this code right now which does not work as expected:

FOR /R D:\Download\758_DATA\ %%F IN (*) DO (
    SET B = %%~pF
    Set B=%B:~-6%  ::take substring of the path
    ECHO.%B%
    ECHO %%F 
    ECHO.
)

推荐答案

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

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

这篇关于如何基于指定的文件夹路径获取目录树中每个文件的相对路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆