Page 1 of 1

Get last string after delimiter FOR /F

Posted: 21 Dec 2011 13:24
by alleypuppy
Hello,

I want to know if it's possible to get the last string after the specified delimiter in a FOR /F loop.

For example, say I have the directory

Code: Select all

C:\WINDOWS\Web\Wallpaper
I want to extract only "Wallpaper" from the string using a FOR /F loop. Or if I have

Code: Select all

C:\Users\[username]\Desktop\Example Folder\Example Folder 2
I want to extract only "Example Folder 2" from the string.

The only problem is I don't know how to set the TOKENS parameter equal to an ever-changing number. Any ideas?

Thanks for the help!

Re: Get last string after delimiter FOR /F

Posted: 21 Dec 2011 14:01
by aGerman
Try:

Code: Select all

set "myPath=C:\Users\[username]\Desktop\Example Folder\Example Folder 2"
for /f "delims=" %%i in ("%myPath%") do set "myFolder=%%~nxi"
echo "%myFolder%"

Regards
aGerman

Re: Get last string after delimiter FOR /F

Posted: 21 Dec 2011 14:07
by !k
or

Code: Select all

call :name "C:\WINDOWS\Web\Wallpaper"
call :name "C:\Users\[username]\Desktop\Example Folder\Example Folder 2"
goto :eof

:name
echo name = %~nx1
goto :eof

Re: Get last string after delimiter FOR /F

Posted: 21 Dec 2011 23:56
by orange_batch
The above works for backslash as a delimiter, but the following works for whatever else:

Code: Select all

call :getlasttoken "what#is#the#last#token"

echo %lasttoken%

pause
exit

:getlasttoken
set "check=%~1"
:loop
if defined check (
for /f "delims=# tokens=1*" %%x in ("%check%") do (
set "lasttoken=%%x"
set "check=%%y"
)
goto loop
) else exit/b