Split variable in 2 after the last dot

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
LiveITA
Posts: 12
Joined: 25 Jan 2018 14:22

Split variable in 2 after the last dot

#1 Post by LiveITA » 12 Mar 2018 20:19

I need to cut variables in two smaller variables after the last dot. For example the variable

Code: Select all

european.union
will be

Code: Select all

vara=european
and

Code: Select all

varb=union
I use the following code to accomplish this purpose:

Code: Select all

for /f "tokens=1 delims=." %%a in ("%elvariato%") do set vara=%%a
for /f "tokens=2 delims=." %%a in ("%elvariato%") do set varb=%%a
The problem is that this code can't manage multiple

Code: Select all

.
split variables. For example the variable

Code: Select all

spain is in.the.european.union
would totally make this code useless.

Code: Select all

vara="spain is in" 

Code: Select all

varb=the
would be the output but i need

Code: Select all

vara="spain is in.the.european"

Code: Select all

varb=union
Don't worry about in var spaces, i can manage them.

I want to split the variable at the last dot

Code: Select all

.
but i don't know how to accomplish that. I tried to read the total number of tokens to merge all the tokens up to N-1 but it did not work. Being unable to know the number of dots before the variable is analyzed by the script makes it kinda hard. Any suggestion?

Squashman
Expert
Posts: 4471
Joined: 23 Dec 2011 13:59

Re: Split variable in 2 after the last dot

#2 Post by Squashman » 12 Mar 2018 21:20

Just use the built-in modifiers of the FOR command.

Code: Select all

@echo off
set "string=spain is in.the.european.union"
FOR %%G IN ("%string%") DO (
	set "vara=%%~nG"
	set "varb=%%~xG
)
set "varb=%varb:~1%"

set var
pause
Output

Code: Select all

vara=spain is in.the.european
varb=union
Press any key to continue . . .

LiveITA
Posts: 12
Joined: 25 Jan 2018 14:22

Re: Split variable in 2 after the last dot

#3 Post by LiveITA » 13 Mar 2018 03:50

perfect thanks. just wondering, why you added the last

Code: Select all

set var
? it has no purpose

Squashman
Expert
Posts: 4471
Joined: 23 Dec 2011 13:59

Re: Split variable in 2 after the last dot

#4 Post by Squashman » 13 Mar 2018 08:05

LiveITA wrote:
13 Mar 2018 03:50
perfect thanks. just wondering, why you added the last

Code: Select all

set var
? it has no purpose
If it has no purpose for you then remove it.

ShadowThief
Expert
Posts: 1163
Joined: 06 Sep 2013 21:28
Location: Virginia, United States

Re: Split variable in 2 after the last dot

#5 Post by ShadowThief » 13 Mar 2018 15:34

LiveITA wrote:
13 Mar 2018 03:50
perfect thanks. just wondering, why you added the last

Code: Select all

set var
? it has no purpose
It displays the values of all variables starting with "var" - it's easier than typing

Code: Select all

echo %vara%
echo %varb%
It's just to show you that it worked.

Post Reply