Jump to content

For loop: split string and echo every token


Recommended Posts

Hey, I've been wondering can I define variable that contains words separated with spaces, then use FOR to go through the string and echo every token?

@echo off

REM DEFINE THE HOSTS THAT SHOULD BE SKIPPED (SEPARATE WITH SPACE)
set DISCARD=DC1 DC2 MGW

FOR /F "delims= " %%a IN ('@echo %DISCARD%') DO @(

echo DISCARDED : %%a
)

but this only echoes the word before the first space.

C:\>skip.cmd
DISCARDED : DC1

C:\>

I know that I could use a text file containing all the words separated with new lines, but for the sake of simplicity I want to define everything inside one variable. I understand that using the "tokens=" parameter I can capture the amount I want from the line, but I just want to echo every token from the line and do something with them.

This is what I would like the output to be:

C:\>skip.cmd
DISCARDED : DC1
DISCARDED : DC2
DISCARDED : MGW

C:\>

Is this possible?

Link to comment
Share on other sites


@ECHO OFF&SETLOCAL
:: DEFINE THE HOSTS THAT SHOULD BE SKIPPED (SEPARATE WITH SPACE)
SET DISCARD=DC1 DC2 MGW
FOR %%a IN (%DISCARD%) DO ECHO/DISCARDED : %%a

Exactly what I was looking for. Thank you! I just don't get what is the difference between FOR %%a IN (%DISCARD%) and FOR %%a IN ('echo %DISCARD%')

Link to comment
Share on other sites

Th difference is

FOR %%a IN (echo %DISCARD%)

echo is a print command, so basically you are asking it to break down something being printed (how do you break down a command???) e.g. for <every part> of (print <variable>) is what you instructed it to do

FOR %%a IN (%DISCARD%)

break down the variable it its commpoent parts

e.g. for <every part> of (<variable>) is what you instructed it to do

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...