Reputation: 1484
Using a batch file, I am trying to get the last foldername in a path.
The batch file gets the current working directory, goes up one level and uses that foldername. The problem is that if the foldername has spaces like "My Project", then the below code will return just "Project".
@echo off
cls
:: get pathnames
set ProjectRoot=%~dp0..\
set ProjectRootLast=%ProjectRoot:~0, -1%
for %%f in (%ProjectRootLast%) do (
set ProjectName=%%~nxf
)
echo %ProjectRoot%
echo %ProjectName%
pause
Upvotes: 0
Views: 413
Reputation: 3452
aschipfl is right, you should use:
@echo off
cls
:: get pathnames
set "ProjectRoot=%~dp0..\"
set "ProjectRootLast=%ProjectRoot:~0,-1%"
for %%f in ("%ProjectRootLast%") do (
set "ProjectName=%%~nxf"
)
echo %ProjectRoot%
echo %ProjectName%
pause
But you could do this much more efficiently using
for %%* in (.) do echo %%~nx*
to get the name of the current directory and
for %%* in (./..) do echo %%~nx*
To get the name of the directory above that
Upvotes: 1