0

I have some string, which is some path C:\A\B\C\D\ How can I get the folder name, say "A" or "B" or other needed. I have solution only for "D":

@echo off setlocal enabledelayedexpansion FOR /f %%i IN ("C:\A\B\C\D\") DO ( set parent=%%~dpi for /F "tokens=*" %%f in ("!parent:~0,-1!") do echo %%~nf ) 

2 Answers 2

2

Next code snippet splits a string to substrings delimited with the \ backslash character. Works with or without a trailing backslash, with or without blank space(s) in a string (path). Note proper quoting in set commands:

@ECHO OFF SETLOCAL enableextensions set "fullpath=C:\Aa\B b\Cc\D d\" set "to_parse="%fullpath:\=" "%"" for %%G in (%to_parse%) do ( echo %%~G %%G ) 

Output:

==>30285354.bat C: "C:" Aa "Aa" B b "B b" Cc "Cc" D d "D d" "" ==> 

Resources (required reading):

Sign up to request clarification or add additional context in comments.

Comments

1

Your question is not clear ("other folder needed" is not a specification) so I assumed you want to separate all folders into array elements, so any desired folder can be get via its index.

@echo off setlocal EnableDelayedExpansion set "string=C:\A\B\C\D\" rem Separate all folders in the string into "folder" array set i=-1 for %%a in ("%string:\=" "%") do ( if %%a neq "" ( set /A i+=1 set "folder[!i!]=%%~a" ) ) rem Show some folders echo The first folder: %folder[1]% echo The second folder: %folder[2]% echo The last folder: !folder[%i%]! 

For further details on arrays in Batch files, see this post.

1 Comment

unfortunately it strips "!" from folder names

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.