Get parent directory name for a particular file using DOS Batch scripting

后端 未结 9 1285
無奈伤痛
無奈伤痛 2020-12-08 21:33

I need to find the name of the parent directory for a file in DOS

for ex.

Suppose this is the directory

C:\\test\\pack\\a.txt
9条回答
  •  一向
    一向 (楼主)
    2020-12-08 22:09

    I found this combination of approaches from the answers of djangofan and paranoid to be both, simple and perfectly sufficient, when looking up my script's parent directory:

    set FULL_PATH=%~dp0
    set FULL_PATH=%FULL_PATH:~1,-1%
    for %%i in ("%FULL_PATH%") do set "PARENT_FOLDER=%%~ni"
    echo %PARENT_FOLDER%
    

    Since you want to work on user input instead, you have to do some minimal additional work, to handle legal variations like C:\foo\bar\a.txt vs. C:\foo\bar\a.txt or c:/foo/bar/a.txt. This might then work for you:

    @setlocal
    @echo off
    
    call:GET_PARENT_FOLDER C:\foo\bar\a.txt
    echo %PARENT_FOLDER%
    call:GET_PARENT_FOLDER C:\foo\bar\\a.txt
    echo %PARENT_FOLDER%
    call:GET_PARENT_FOLDER c:/foo/bar/a.txt
    echo %PARENT_FOLDER%
    
    pause
    goto:EOF
    
    :GET_PARENT_FOLDER
    :: Strip the filename, so we get something like this: 'C:\foor\bar\'
    set "_FULL_PATH=%~dp1"
    
    :: Strips all dangling '\' and '/' in a loop, so the last folder name becomes accessible
    :_STRIP
    if not "%_FULL_PATH:~-1%"=="\" if not "%_FULL_PATH:~-1%"=="/" goto:_STRIP_END
    set "_FULL_PATH=%_FULL_PATH:~1,-1%"
    goto:_STRIP
    :_STRIP_END
    
    :: We need the context of a for-loop for the special path operators to be available
    for %%i in ("%_FULL_PATH%") do set "PARENT_FOLDER=%%~ni"
    
    goto:EOF
    

提交回复
热议问题