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
for %%a in (.) do set currentfolder=%%~na echo %currentfolder% From here: https://superuser.com/questions/160702/get-current-folder-name-by-a-dos-command
c:\parent\child.01. An additional 'x' character should be added to work correctly: currentfolder=%%~nxaHere is the answer
for %%a in ("%cd%") do set folder=%%~na echo.%folder% pause %~ modifiers can only be used on file or folder names, but "%cd%" is a STRING! Apparently, the string is processed as a name no matter its contents. Try this: for %a in ("@:\one;\two()\three=+") do echo %~da %~na %~fa@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"