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

时间:2016-01-22 08:57:42

标签: windows batch-file cmd

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

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

3 个答案:

答案 0 :(得分:10)

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

答案 1 :(得分:4)

正如npocmaka正确建议的那样,从%PATH%(或any of these other environment variables)中选择一个不同的变量。其次,确保您的脚本使用setlocal以避免使用此脚本中的变量来阻止控制台会话的环境。第三,只需为要导航的每个祖先添加\..即可。无需担心子串操作。

@echo off
setlocal

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

答案 2 :(得分:1)

可以使用一个小的子例程来获取文件的第一父文件(基本目录),该子例程返回文件的~dp:GetFileBaseDir的路径,在下面的示例中。< / p>

感谢@rojo提供一种实现多个父母的目标的方法。我将他的解决方案包含在子例程: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
相关问题