Batch - Split directory name on folder parts?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
gerganag
Posts: 8
Joined: 04 Jun 2013 02:07

Batch - Split directory name on folder parts?

#1 Post by gerganag » 04 Jun 2013 02:12

hi,

I need to split the following directory on its parts:
C:\folder1\folder2\folder3\folder4\ (I don't know in advance how long will the path be)
and to take folder4 and folder3 (the last two folders) in a variables.

Hope anyone can help me?
Thank you in advance,
Gerry

foxidrive
Expert
Posts: 6033
Joined: 10 Feb 2012 02:20

Re: Batch - Split directory name on folder parts?

#2 Post by foxidrive » 04 Jun 2013 03:15

Code: Select all

@echo off
set "var=C:\folder1\folder2\folder3\folder4\"
for %%a in ("%var%\.") do (
for %%b in ("%%~dpa\.") do (
echo "%%~nxb" "%%~nxa"
)
)
pause



Gerry, you may mean well but "thank you in advance" is a lazy way of saying 'I'll never return to tell you that it worked and to thank you for real'.
I don't know why it became such a commonly used phrase.

gerganag wrote:Thank you in advance,
Gerry

gerganag
Posts: 8
Joined: 04 Jun 2013 02:07

Re: Batch - Split directory name on folder parts?

#3 Post by gerganag » 04 Jun 2013 04:39

hi foxidrive,

Thank you so much for the suggestion. I think I can use it :)

as for the "Thank you in advance" - it has become more of a habit writing this down...

Have a lovely day,
Gerry

Endoro
Posts: 244
Joined: 27 Mar 2013 01:29
Location: Bozen

Re: Batch - Split directory name on folder parts?

#4 Post by Endoro » 04 Jun 2013 08:14

my try:

Code: Select all

@echo off&setlocal
set "var=C:\folder1\folder2\folder3\folder4\"
REM do not touch the empty lines
set LF=^


REM do not touch the empty lines
setlocal enabledelayedexpansion
set "var=%var:\=!LF!%"
for %%i in (%var%) do (
   set /a counter+=1
   set "var!counter!=%%i"
)
set "var"


..output is:

Code: Select all

var=C:
folder1
folder2
folder3
folder4

var1=C:
var2=folder1
var3=folder2
var4=folder3
var5=folder4

Aacini
Expert
Posts: 1680
Joined: 06 Dec 2011 22:15
Location: México City, México

Re: Batch - Split directory name on folder parts?

#5 Post by Aacini » 04 Jun 2013 11:16

My version:

Code: Select all

@echo off
setlocal EnableDelayedExpansion

set "var=C:\folder1\folder2\folder3\folder4\"

for %%a in (%var:\= %) do (
   set lastButOne=!lastFolder!
   set lastFolder=%%a
)

echo Last folder:  %lastFolder%
echo Last but one: %lastButOne%

Output is:

Code: Select all

Last folder:  folder4
Last but one: folder3

The version below correctly manage folder names with spaces:

Code: Select all

@echo off
setlocal EnableDelayedExpansion

set "var=C:\folder 1\folder 2\folder 3\folder 4\"

if "%var:~-1%" equ "\" set var=%var:~0,-1%
set var=%var:\=" "%
for %%a in ("%var%") do (
   set lastButOne=!lastFolder!
   set lastFolder=%%~a
)

echo Last folder:  %lastFolder%
echo Last but one: %lastButOne%


Antonio

Post Reply