D a
D a

Reputation: 3

Using FOR command, attempting to parse a comma-delimited list embedded with blanks

I am attempting to use FOR to parse a list delimited with commas and embedded with blanks.

Example:

SET "X=My Town,Four square,a b c d"

I know

FOR "delims=," %%Q IN (%X%) DO ECHO '%%Q' 

doesn't work, but it indicates my intent. I want three lines produced

My Town
Four square
a b c d

Upvotes: 0

Views: 121

Answers (4)

Aacini
Aacini

Reputation: 67236

Perhaps this is the simplest one:

@echo off
setlocal EnableDelayedExpansion

SET "X=My Town,Four square,a b c d"

echo !X:,=^
%Don't remove this line%
!

Output:

My Town
Four square
a b c d

This is a replacement of a comma by a LineFeed character like in Squashman's answer above but that is not generated in a FOR command, it is directly generated in the echo command itself...

Upvotes: 2

Magoo
Magoo

Reputation: 80183

How about

@ECHO OFF
SETLOCAL
SET "X=My Town,Four square,a b c d"

FOR %%Q IN ("%X:,=","%") DO ECHO %%~Q

GOTO :EOF

Works for me!

Upvotes: 2

Squashman
Squashman

Reputation: 14320

This concept comes from DosTips.com which replaces a delimiter with a linefeed so that the FOR /f command treats each field as a line.

@echo off
setlocal EnableDelayedExpansion
SET "X=My Town,Four square,a b c d"
for /F "delims=" %%G in (^"!X:^,^=^
% Do NOT remove this line %
!^") do (
  echo %%G
)

Output

D:\My Drive\BatchFiles>FOR_F_LF.bat
My Town
Four square
a b c d

Upvotes: 2

Compo
Compo

Reputation: 38708

Just for added confusion...

@Echo Off
SetLocal EnableExtensions EnableDelayedExpansion

Set "X=My Town,Four square,a b c d"

Set "i=1"
Set "X[!i!]=%X:,=" & Set /A i += 1 & Set "X[!i!]=%"
For /L %%G In (1,1,!i!) Do If Defined X[%%G] Echo !X[%%G]!

Pause

You could learn more about the underlying technique here

Upvotes: 2

Related Questions