Get directory name from path of

2019-01-22 13:33发布

Given that the current directory, %CD% is

C:\Parent\Child

In a batch file, how can I get the value Child in to a variable?

thanks

4条回答
爷的心禁止访问
2楼-- · 2019-01-22 14:19

@manojlds's answer is not correct for all cases.

The %%~nI shortcut works fine for files, but not for directories.

Example:

C:\a..o\ex.bat

@ECHO OFF
FOR %%a IN (.) DO SET currentfolder=%%~na
ECHO %currentfolder%

If I execute this batch file from its location, the output is "a.":

C:\a..o\>ex.bat
a.

Solution:

A possible solution is the following:

C:\sol.bat

@ECHO OFF
SETLOCAL
SET cwd="\%~f1"
SET name=""
:extract
    SET char="%cwd:~-2,-1%"
    IF NOT %char%=="\" (
        SET cwd="%cwd:~1,-2%"
        SET name="%char:~1,-1%%name:~1,-1%"
        GOTO :extract
    )
ECHO %name%
ENDLOCAL

Tests:

C:\>sol.bat "@!%#"
"@!%#"
C:\>sol.bat a..o
"a..o"
查看更多
forever°为你锁心
3楼-- · 2019-01-22 14:21

Here is the answer

for %%a in ("%cd%") do set folder=%%~na
echo.%folder%
pause
查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-22 14:22

or you can do something like this

@ECHO OFF
FOR %%a IN (.) DO SET currentfolder=%%~nxa
ECHO %currentfolder%
查看更多
做自己的国王
5楼-- · 2019-01-22 14:31
for %%a in (.) do set currentfolder=%%~na
echo %currentfolder%

From here: https://superuser.com/questions/160702/get-current-folder-name-by-a-dos-command

查看更多
登录 后发表回答