Batch file For Loop help

April 2, 2010 at 12:30:38
Specs: Windows Vista
I'm writing a batch file and I'm trying to parse out the name of the current directory.

Example:
current directory = "C:\test directory\001_TestFolder"

desired string = "001_TestFolder"

I can't figure out how to parse out the string to retrieve the last token.


See More: Batch file For Loop help

Report •

#1
April 2, 2010 at 13:41:12
i think i saw a better way a while back, but don't know how to retreive it. so, this might serve:
for /f "tokens=*" %%a in ("%cd%") do set cdir=%%~na
echo.%cdir%

Report •

#2
April 2, 2010 at 13:51:06
There must be a better way to do this. I wish I knew what it was.

==================================

@echo off & setLocal EnableDELAYedeXpansion

for /f "tokens=* delims=" %%a in ("%CD%") do (
  set S=%%a
  set S=!S:\= !
  call :sub1 !S!
)

echo.!last!

goto :eof

:sub1
  :loop
    if "%2" neq "" (
    shift
    goto :loop
    )
set last=%1

goto :eof


=====================================
Helping others achieve escape felicity

M2


Report •

#3
April 2, 2010 at 14:06:17
OI VEY!


=====================================
Helping others achieve escape felicity

M2


Report •

Related Solutions

#4
April 2, 2010 at 14:14:48
Awesome! Thanks that worked!

Report •

#5
April 2, 2010 at 15:31:02
I don't understand the logic behind the code...
for /f "tokens=*" %%a in ("%cd%") do set cdir=%%~na

can someone explain to me what %%~na does and why tokens=* is used?


Report •

#6
April 2, 2010 at 21:52:23
go to command prompt and type:
for /?
set /?
setlocal /?
this gives a good idea of what's going on. basically the tilde-n says to extract the last element from a path-string.
(actually, should probably have put: %%~nxa in my fix, in case the directory has an extension). tokens are the elements of any given string, and are like words in a sentence separated by delimiters (like words have spaces, or commas, etc. between them.) batchscript defaults to tokenizing on spaces and tabs, and so i put tokens=* (that is, * means "all") in order to get the whole string instead of just the first "word", in case your path had spaces (yech!) in it.

Report •

#7
April 5, 2010 at 04:37:51
This works as well (using some extra tools) :

C:\>set directory="C:\test directory\001_TestFolder"

C:\>echo %directory% | awk.exe -F\ " { print $NF } " | sed.exe "s/\"//g"
001_TestFolder

C:\>


Report •

Ask Question