在批处理脚本中获取特定路径的父目录

11

你好,我有一个批处理文件中的完整文件路径变量。如何获取其父目录路径的第一和第二层?


set path=C:\SecondParent\FirstParent\testfile.ini

%dppath% 这个行得通吗?我知道对于数字参数(%dp1)是可以的。 - Andy Nugent
3个回答

20
不要使用变量PATH。%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%

它只给出了它的第一个父目录。但我需要它的祖先目录。如何获得这个? - selvakumar
1
两个输出相同的值。 - selvakumar
@SelvakumarGurusamy - 已修复 - npocmaka
3
我会将第二个for循环更改为以下形式:for /D %%a in ("%p_dir%..") do set "p2_dir=%%~dpa"。这样可以去掉结尾的反斜杠,避免在父级目录已经是驱动器根目录时出现问题,因为循环会接收到例如“D:”的内容,这表示驱动器“D:”的当前目录;我的建议返回驱动器“D:”的根目录... - aschipfl

8
正如npocmaka所建议的那样,从%PATH%(或任何其他环境变量这里)中选择一个不同的变量。其次,请确保您的脚本使用setlocal以避免在此脚本中使用变量垃圾填充控制台会话的环境。第三,只需添加\..以导航到每个祖先即可,无需烦扰子字符串操作。
@echo off
setlocal

set "dir=C:\SecondParent\FirstParent\testfile.ini"
for %%I in ("%dir%\..\..") do set "grandparent=%%~fI"
echo %grandparent%

是的,我理解了。谢谢您宝贵的信息。 - selvakumar
很好。\.. 比类似于加密的 DOS 语法如 %varname:~0,-1% 更加清晰。 - mwag

1
可以使用一个小子程序来获取文件的第一个父级(基本目录),该子程序返回文件的~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:\"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接