Search code examples
batch-filetokendelimiter

Batch file extracting last token from unknown number of delimiters


I've tried the other answers that are similar to my question, but they are not working. I set a variable "name" which is delimited by periods. Some users have two tokens (e.g., "Bob.Smith") and some users have three (e.g., "Bob.J.Smith"). I just need to extract the last token from the "name" string and store it back into the "name" variable. This is what I have:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
set name=%USERNAME%
for /f "tokens=* delims=." %%A in ("%name%") do (
    set name=%%A
    echo !name!
    echo %%A
)

But it just returns the full initial "name" variable value.

I've also tried the following with no luck.

for /f "delims=." %%A in ("%name%") do set name=%%~nxA

Please help!


Solution

  • you can try like this:

    set "name=Bob.J.Smith"
    for %%a in ("%name:.=" "%") do set "last=%%~a"
    echo %last%