Loop over folder string and parse out last folder name

后端 未结 13 1439
-上瘾入骨i
-上瘾入骨i 2020-12-03 05:39

I need to grab the folder name of a currently executing batch file. I have been trying to loop over the current directory using the following syntax (which is wrong at prese

13条回答
  •  情深已故
    2020-12-03 06:19

    This question's a little old, but I've looked for a solution more than once so here's a completely new take on it that I've just put together.

    The trick is that we take the desired path, back up one level to create a folder mask for substitution and then replace the folder mask with nothing.

    To test it, simple copy and paste into a command script (.cmd) in any directory, then run it. It will spit out only the deepest directory you're currently in.

    Notes:

    • Replace %~dp0 with whatever path you like (as it is, it will return the deepest folder the batch file is run from. This is not the same as %cd%.)
    • When specifying the 'pathtofind' variable ensure there are no quotes e.g. c:\some path and not "c:\some path".
    • The original idea for folder masking is mine
    • Spaces in the path are no problem
    • Folder depth is not a problem
    • It was made possible by the genius of this batch scripting tip http://www.dostips.com/DtCodeBatchFiles.php#Batch.FindAndReplace

    Hope this helps someone else.

    @echo off
    set pathtofind=%~dp0
    if not exist %pathtofind% echo Path does not exist&pause>nul&goto :eof
    
    cd /d %pathtofind%
    set path1=%cd%
    cd ..
    set path2=%cd%
    
    call set "path3=%%path1:%path2%\=%%"
    
    echo %path3%
    
    pause>nul
    

提交回复
热议问题