Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop over folder string and parse out last folder name

I need to grab the folder name of a currently executing batch file. I have been trying to loop over the current directory using the following syntax (which is wrong at present):

set mydir = %~p0
for /F "delims=\" %i IN (%mydir%) DO @echo %i

Couple of issues in that I cannot seem to pass the 'mydir' variable value in as the search string. It only seems to work if I pass in commands; I have the syntax wrong and cannot work out why.

My thinking was to loop over the folder string with a '\' delimiter but this is causing problems too. If I set a variable on each loop then the last value set will be the current folder name. For example, given the following path:

C:\Folder1\Folder2\Folder3\Archive.bat

I would expect to parse out the value 'Folder3'.

I need to parse that value out as its name will be part of another folder I am going to create further down in the batch file.

Many thanks if anyone can help. I may be barking up the wrong tree completely so any other approaches would be greatly received also.

like image 522
Tim Peel Avatar asked Nov 11 '08 14:11

Tim Peel


3 Answers

After struggling with some of these suggestions, I found an successfully used the following 1 liner (in windows 2008)

for %%a in (!FullPath!) do set LastFolder=%%~nxa
like image 110
Jonathan Avatar answered Nov 06 '22 08:11

Jonathan


You were pretty close to it :) This should work:

@echo OFF
set mydir="%~p0"
SET mydir=%mydir:\=;%

for /F "tokens=* delims=;" %%i IN (%mydir%) DO call :LAST_FOLDER %%i
goto :EOF

:LAST_FOLDER
if "%1"=="" (
    @echo %LAST%
    goto :EOF
)

set LAST=%1
SHIFT

goto :LAST_FOLDER

For some reason the for command doesn't like '\' as a delimiter, so I converted all '\' to ';' first (SET mydir=%mydir:\=;%)

like image 10
Patrick Cuff Avatar answered Nov 06 '22 06:11

Patrick Cuff


I found this old thread when I was looking to find the last segment of the current directory. The previous writers answers lead me to the following:

FOR /D %%I IN ("%CD%") DO SET _LAST_SEGMENT_=%%~nxI
ECHO Last segment = "%_LAST_SEGMENT_%"

As previous have explained, don't forget to put quotes around any paths create with %_LAST_SEGMENT_% (just as I did with %CD% in my example).

Hope this helps someone...

like image 6
Paul Margetts Avatar answered Nov 06 '22 06:11

Paul Margetts