gpt4 book ai didi

batch-file - cmd 批处理 - usebackq 为 : string to split altered from comma separated to space separated

转载 作者:行者123 更新时间:2023-12-03 23:59:48 25 4
gpt4 key购买 nike

我想读取一个包含多个(未终止的)Kafka 主机的字符串,并使用 cmd for 将它们列出在单独的行中。

字符串如下:

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

我所拥有的是:

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.
)

但是,我只将所有主机放在一行中,以空格分隔:

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

为什么?

如果我打开@echo on,我会看到这个,这是没有意义的:

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

如果仔细观察,当 %BOOTSTRAPSERVERS% 没有双引号时,echo 会将字符串从逗号分隔变为空格分隔。

如果是双引号,输出将为:

"host1:9092

为什么?

是否有更好的方法来用分隔符分割字符串?

最佳答案

要按标准分隔符(空格、制表符、逗号)分割字符串,您可以使用普通的 for 循环(无 /f):

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

输出:

host1:9092
host2:9092
host3:9092

请注意 set 命令的语法(这样引号就不会成为值的一部分)。相同的语法适用于 set/p:set/p "var=Prompt:"

关于batch-file - cmd 批处理 - usebackq 为 : string to split altered from comma separated to space separated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59771342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com