Solved Getting last subfolder in a tree

Various / CUSTOM BUILT
November 25, 2016 at 01:20:06
Specs: Windows 10, Intel i7 4770k, 32GB 1600MHz RAM
I have a path like this: C:\Users\User\test\subfolder\

I need to get only "subfolder", in this case. I tried this, where %1 is the path:

CD /D "%~DP1"
SET M_CD=%CD%
CD..
SET N_CD=%CD%
SET DIR=%M_CD:!N_CD!=%
SET DIR=!DIR:\=!

But for some reason, !N_CD! and !M_CD! are equal, so it doesn't work.
Why are the two variables equal and is there a different way to do this?

Don't worry if plan A fails, there are 25 more letters in the alphabet ;)

message edited by RainBawZ


See More: Getting last subfolder in a tree

Report •


#1
November 25, 2016 at 01:53:00
✔ Best Answer

Report •

#2
November 25, 2016 at 02:51:58
Thanks, ijack. I guess I should've googled some more :P
Do you have any idea why my approach didn't work?

Don't worry if plan A fails, there are 25 more letters in the alphabet ;)


Report •

#3
November 26, 2016 at 21:42:23
Hi again:

Mainly your concept worked except you got the ! and % reversed. (I always forget which one to put outside). Here is yours with markers reversed:
:: ------- begin bat
@echo off & setlocal enabledelayedexpansion
rem CD /D "%~DP1" took this out for my tests
SET M_CD=%CD%
echo top: %M_CD%
CD..
:: note the inclusion of the backslash to filter it out
SET N_CD=%CD%\
echo next: %N_CD%
SET DIR=!M_CD:%N_CD%=!
:: this was the reversed in your code
rem SET DIR=%M_CD:!N_CD!=%
echo dir: %DIR%
SET DIR=!DIR:\=!
::--------- end script 1
I know someone wrote this same scenario long in the murky past on this forum, but I decided it's quicker to re-write than to do historical research. This was my option:

@echo off & setlocal
:: return the path and last level for any given level in tree struct either given or actual
set lvl=%1
:: optional string to parse - MUST have initial \ if supplied, else curr.dir will interfere
set x=%2
if not defined x set x=%cd%
if not defined lvl set lvl=1
echo working: %x%
echo back-recursion %lvl% levels:
for /l %%i in (1 1 %lvl%) do call :aa
echo path: %x%
echo last level: %y%
goto :eof

:aa
for %%a in (%x%) do (
set x=%%~pa
set y=%%~nxa
)
echo %x% -- %y%
:: unless the terminal slash is removed, the back-recursion will fail
set x=%x:~0,-1%
:: all-the-way
rem if defined x goto :aa


Report •
Related Solutions


Ask Question