你好,我有一个批处理文件中的完整文件路径变量。如何获取其父目录路径的第一和第二层?
set path=C:\SecondParent\FirstParent\testfile.ini
你好,我有一个批处理文件中的完整文件路径变量。如何获取其父目录路径的第一和第二层?
set path=C:\SecondParent\FirstParent\testfile.ini
@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%
for
循环更改为以下形式:for /D %%a in ("%p_dir%..") do set "p2_dir=%%~dpa"
。这样可以去掉结尾的反斜杠,避免在父级目录已经是驱动器根目录时出现问题,因为循环会接收到例如“D:”的内容,这表示驱动器“D:”的当前目录;我的建议返回驱动器“D:”的根目录... - aschipfl@echo off
setlocal
set "dir=C:\SecondParent\FirstParent\testfile.ini"
for %%I in ("%dir%\..\..") do set "grandparent=%%~fI"
echo %grandparent%
\..
比类似于加密的 DOS 语法如 %varname:~0,-1%
更加清晰。 - mwag~dp
路径,例如下面的:GetFileBaseDir
和:GetFileBaseDirWithoutEndSlash
。: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)是可以的。 - Andy Nugent