Chaos
Chaos

Reputation: 15

Multiple spaces in a for /f loop

I need to separate a string based on spaces, but only after the first space. However, the second string returns only one word.

The code I'm currently using is this:

@echo off
set string=alone these are together
for /f "tokens=1 " %%g IN ("%string%") do set first=%%g
for /f "tokens=2*" %%g IN ("%string%") do set second=%%g
echo %first%
echo %second%
pause

Right now, my output is alone these, but I want alone these are together.

Am I setting the variable wrong, or is my sytax on the token option incorrect?

Upvotes: 0

Views: 48

Answers (1)

SomethingDark
SomethingDark

Reputation: 14325

* is its own token in the token list, so "tokens=2*" %%g puts the second token in %string% in %%g and everything after it in %%h.

for /f "tokens=1,*" %%g IN ("%string%") do (
    set "first=%%g"
    set "second=%%h"
)

will put the first the first token in %first% and everything else in %second%.

Upvotes: 1

Related Questions