Search code examples
batch-filecmdecho

cmd batch - usebackq in for: string to split altered from comma separated to space separated


I want to read a string containing several(number unterminated) hosts of Kafka and list them in separate lines with cmd for.

The string is like:

host1:9092,host2:9092,host3:9092,...

And what I have is:

set /p BOOTSTRAPSERVERS="Bootstrap servers with port, separated by comma(by default localhost:9092): "
REM echo "%BOOTSTRAPSERVERS%"
if "%BOOTSTRAPSERVERS%"=="" set BOOTSTRAPSERVERS="localhost"

echo All the servers to connect: 
FOR /F "usebackq delims=," %%i in (`echo %BOOTSTRAPSERVERS%`) do (
    echo %%i
    echo.
)

But, I only get all the hosts in one line, space separated:

All the servers to connect:
host1:9092 host2:9092 host3:9092

Why?

If I turn on @echo on, I see this, which does not make sense:

set /p BOOTSTRAPSERVERS="Bootstrap servers with port, separated by comma(by default localhost:9092): "
Bootstrap servers with port, separated by comma(by default localhost:9092): host1:9092,host2:9092,host3:9092

REM echo "host1:9092,host2:9092,host3:9092"

if "host1:9092,host2:9092,host3:9092" == "" set BOOTSTRAPSERVERS="localhost"

echo All the servers to connect:
All the servers to connect:

FOR /F "usebackq delims=," %i in (`echo host1:9092 host2:9092 host3:9092`) do (
echo %i
 echo.
)

(
echo host1:9092
 echo.
)
host1:9092

If you observe carefully, echo turns the string from comma separated into space separated, when %BOOTSTRAPSERVERS% is not double quoted.

If it is double quoted, the output will be:

"host1:9092

Why?

Is there a better way to split a string with delimiters?


Solution

  • To split a string by standard delimiters (SPACE, TAB, Comma), you can use a plain for loop (no /f):

    set "bootstrapservers=host1:9092,host2:9092,host3:9092"
    for %%a in (%bootstrapservers%) do echo %%a
    

    Output:

    host1:9092
    host2:9092
    host3:9092
    

    Note the syntax for the set command (this way the quotes don't become part of the value). Same syntax works with set /p: set /p "var=Prompt:"