批处理编程 - 获取文件的相对路径 [英] batch programming - get relative path of file
问题描述
使用DOS批处理,我要循环递归的目录,并阅读全文件路径,以及获得该文件的相对路径。例如,位于文件D:\\富\\酒吧\\ A \\ B \\ file.txt的将获得相对路径:\\酒吧\\ A \\ B \\
Using DOS batch, I want to loop recursively through a directory and read the fully file path, plus get the relative path of that file. For example, a file located in "D:\foo\bar\a\b\file.txt" will get the relative path: "\bar\a\b\"
现在我用这个code和它不工作
Right now I'm using this code and it does not work
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.
)
任何人都可以帮忙吗?
Anyone can help, please?
推荐答案
我不知道你想完成什么,但至少这会给你一个很好的起点:
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
::take substring of the path
set B=!B:~0,-6!
echo Full : %%F
echo Partial: !B!
echo.
)
既然你在循环中修改一个变量,你需要告诉你希望允许变量被扩大了与延时命令间preTER。这是 SETLOCAL enabledelayedexpansion
是什么。然后你可以使用!
如写成这样的VAR分隔符,而不是%
,和变量在运行时进行扩展。这是必要的,因为为
-loop将被称为像它是1单呼(你可以看到,当你离开了呼应了
)
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 var 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 1 single call (you can see this when you leave out the echo off
)
修改:修订后的例子,其中包括自动切断:
Edit: revised example which includes automatic cut off:
@echo off & setlocal enabledelayedexpansion
set rootdir=%~f1
set foo=%rootdir%
set cut=
:loop
if not "!foo!"=="" (
set /a cut += 1
set foo=!foo:~1!
goto :loop
)
echo Root dir: %rootdir%
echo strlen : %cut%
:: also remove leading /
set /a cut += 1
for /R %rootdir% %%F in (*) do (
set B=%%~fF
::take substring of the path
set B=!B:~%cut%!
echo Full : %%F
echo Partial : !B!
echo""
)
这篇关于批处理编程 - 获取文件的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!