Reputation: 323
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
)
Upvotes: 0
Views: 572
Reputation: 67296
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.
Upvotes: 1
Reputation: 30258
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):
%~G
etc. special page) Command Line arguments (Parameters)Upvotes: 2