Windows 获取批处理脚本中特定路径的父目录
嗨,我在批处理文件变量中有完整的文件路径。如何获取其第一级和第二级父目录路径Windows 获取批处理脚本中特定路径的父目录,windows,batch-file,cmd,Windows,Batch File,Cmd,嗨,我在批处理文件变量中有完整的文件路径。如何获取其第一级和第二级父目录路径 set path=C:\SecondParent\FirstParent\testfile.ini 不要对此使用变量。%PATH%是命令提示符使用的内置变量 @echo off set "_path=C:\SecondParent\FirstParent\testfile.ini" for %%a in ("%_path%") do set "p_dir=%%~dpa" echo %p_dir% for %%a in
set path=C:\SecondParent\FirstParent\testfile.ini
不要对此使用变量。%PATH%是命令提示符使用的内置变量
@echo off
set "_path=C:\SecondParent\FirstParent\testfile.ini"
for %%a in ("%_path%") do set "p_dir=%%~dpa"
echo %p_dir%
for %%a in (%p_dir:~0,-1%) do set "p2_dir=%%~dpa"
echo %p2_dir%
正如Npcmaka正确建议的那样,从
%PATH%
(或)中选择一个不同的变量。其次,确保脚本使用setlocal
,以避免使用脚本中的变量破坏控制台会话的环境。第三,只需为您想要导航的每个祖先添加一个\..
。无需费心处理子字符串
@echo off
setlocal
set "dir=C:\SecondParent\FirstParent\testfile.ini"
for %%I in ("%dir%\..\..") do set "grandparent=%%~fI"
echo %grandparent%
在下面的示例中,可以使用一个小的子例程来获取文件的第一个父级(基本目录),该子例程返回文件的
~dp
路径:GetFileBaseDir
和:GetFileBaseDirWithoutEndSlash
感谢@rojo为多位家长提供了实现这一目标的方法。我将他的解决方案封装在一个子例程:GetDirParentN
中,使其更有用
@echo off
setlocal
REM Initial file path
set "pathTestFile=C:\SecondParent\FirstParent\testfile.ini"
echo pathTestFile: "%pathTestFile%"
REM First level parent (base dir)
REM with ending backslash
call :GetFileBaseDir dirFileBase "%pathTestFile%"
echo dirFileBase: "%dirFileBase%"
REM Same but without ending backslash
call :GetFileBaseDirWithoutEndSlash dirFileBaseWithBackSlash "%pathTestFile%"
echo dirFileBaseWithBackSlash: "%dirFileBaseWithBackSlash%"
echo.
REM Based on @rojo answer, using subroutine
REM One level up
call :GetDirParentN dirFileParent1 "%pathTestFile%" ".."
echo dirFileParent1: "%dirFileParent1%"
REM Two levels up
call :GetDirParentN dirFileParent2 "%pathTestFile%" "..\.."
echo dirFileParent2: "%dirFileParent2%"
REM Three levels up
call :GetDirParentN dirFileParent3 "%pathTestFile%" "..\..\.."
echo dirFileParent3: "%dirFileParent3%"
exit /b 0
:GetFileBaseDir
:: sets the value to dirFileBase variable
set "%~1=%~dp2"
exit /b 0
:GetFileBaseDirWithoutEndSlash
set "dirWithBackSlash=%~dp2"
REM substring from the start to the end minus 1 char from the end
set "%~1=%dirWithBackSlash:~0,-1%"
exit /b 0
:GetDirParentN
for %%I in ("%~2\%~3") do set "%~1=%%~fI"
exit /b 0
输出:
pathTestFile: "C:\SecondParent\FirstParent\testfile.ini"
dirFileBase: "C:\SecondParent\FirstParent\"
dirFileBaseWithBackSlash: "C:\SecondParent\FirstParent"
dirFileParent1: "C:\SecondParent\FirstParent"
dirFileParent2: "C:\SecondParent"
dirFileParent3: "C:\"
%dppath%可以工作吗?我知道它适用于带编号的参数(%~dp1)。它给出了它的第一个父目录。但我也需要它来授予父目录。如何获得该值?两个打印相同的值。@SelvakumarGurusamy-fixedI会将循环的第二个
更改为:对于(“%p_dir%”中的/D%%a,设置“p2_dir=%%~dpa”
;您正在删除尾随的反斜杠,如果第一级父级已经是驱动器的根,这可能会有问题,因为循环将接收e。gD:
,表示驱动器的当前目录D:
;我的建议返回驱动器D:
…是的,我明白了。谢谢你的宝贵信息。很好<代码>\..
比晦涩的DOS语法更清晰,例如%varname:~0,-1%