Mike B
Mike B

Reputation: 35

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!

Upvotes: 1

Views: 1632

Answers (3)

Squashman
Squashman

Reputation: 14290

Here is another option that uses the SET command with the & to concatenate multiple string substitutions.

@echo off

set "name=Bob.J.Smith"
set "name=%name:.=" & set "name=%"
echo %name%
pause 

Upvotes: 3

npocmaka
npocmaka

Reputation: 57252

you can try like this:

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

Upvotes: 4

Magoo
Magoo

Reputation: 79983

for %%A in ("%name%") do set name=%%~xA
echo %name:~1%

Interpreting name as a filename, select the extension part only and assign to name.

Then display name starting at "character 1" where the string starts at character 0.

Upvotes: 2

Related Questions