Reputation: 2201
I have this code, but it doesn't seem to be working; I can't work out why:
set dir = %cd%
:char
set dir=%dir:~0,-1%
IF %dir:~-1%=="\" ( goto end ) else ( goto char )
:end
I have narrowed it down to the line
set dir=%dir:~0,-1%
which seems to be setting dir
to ~0,-1
, but that doesn't make sense because I used the exact same line in another program, and it worked fine.
BTW: This code is meant to be removing the last folder name from the current directory path.
Thanks in advance for any help.
Upvotes: 1
Views: 4664
Reputation: 57
In my case, I've done it easily by:
for %%a in (%FilePath%) do set "ParentDir=%%~dpa"
echo %ParentDir%
%%~dpa expands the %a to (d)drive and (p)path
Upvotes: 1
Reputation: 34989
The actual problem in your code is that the variable dir
is not assigned in the first line, its name is dir
+ SPACE. You need to change it to set dir=%cd%
or even set "dir=%cd%"
.
To remove the last folder name from a given path, use a simple for
loop and the ~dp
expansion (see for /?
):
set "FOLDER=%CD%"
for /D %%D in ("%FOLDER%") do (
set "PARENT=%%~dpD"
)
echo Last folder removed: %PARENT%
The is no need to split off character by character and search for \
as you are doing.
Note:
I recommend not to use variable name dir
to avoid confusion as there is an equally named internal command.
Upvotes: 3
Reputation: 80213
@ECHO Off
SETLOCAL
set "dir=%cd%"
:char
set dir=%dir:~0,-1%
IF "%dir:~-1%"=="\" ( goto end ) else ( goto char )
:end
SET di
FOR /f %%a IN ("%cd%") DO SET "dir=%%~dpa"
SET di
GOTO :EOF
set
recognises Space on each side of the assignment, hence you were assigning the current directory to "dirSpace" and dir
was not set at all.
Your if
command was missing the quotes around the first argument.
Here's an easier way to do it...
Upvotes: 1