Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

* 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%.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading