[英]Echo Without Newline in a Windows Batch `for` Loop
Please note: This question is not about how to echo without a newline. 请注意:此问题不是关于如何在没有换行符的情况下进行回显。 It's about to pipe a variable without a newline and store the result in another variable.
它将通过管道传递不带换行符的变量,并将结果存储在另一个变量中。 Please don't mark this question as duplicate to other questions answering only how to remove newlines!
请不要将此问题标记为与仅回答如何删除换行符的其他问题重复!
I have a variable a
which I want to pass to a program (let's use more
for the sake of this example), and its result should be stored into another variable b
. 我有一个变量
a
,我想传递给程序(在此示例中,我们more
使用它),其结果应存储在另一个变量b
。 This is to prevent the creation of temporary files. 这是为了防止创建临时文件。 Sticking some answers from other questions here together, this could be achieved by something like this:
将其他问题的一些答案汇总在一起,可以通过以下方式实现:
FOR /f "tokens=*" %%t IN ('ECHO %a% ^| MORE') DO SET b=%%t
Which works -- BUT will add another newline on my variable! 哪个有效-但是会在我的变量上添加另一个换行符! So I tried the following tricks you find on stackoverflow/superuser to prevent the newline.
因此,我尝试了以下在stackoverflow / superuser上发现的技巧,以防止换行。 If you do these without the loop, they work perfectly!
如果您不循环执行这些操作,它们将完美工作! But once you put them in a loop, they fail:
但是一旦将它们置于循环中,它们就会失败:
FOR /f "tokens=*" %%t IN ('ECHO ^| SET /p="%a%" ^| MORE') DO SET b=%%t
FOR /f "tokens=*" %%t IN ('^<NUL SET /p="%a%" ^| MORE') DO SET b=%%t
It will always say The syntax of the command is incorrect.
它将始终
The syntax of the command is incorrect.
What am I missing? 我想念什么? Please help me!
请帮我!
If you run your command 如果您运行命令
FOR /f "delims=" %%t IN ('^<NUL SET /p="%a%" ^| more ') DO SET "b=%%t"
with echo
ON you will see the equal sign in the set
command has vanished, it has been removed by the parser leaving an incorrect command. 在
echo
开启的情况下,您会看到set
命令中的等号消失了,解析器将其删除,留下了不正确的命令。
You have two options: 您有两种选择:
FOR /f "delims=" %%t IN ('^<NUL SET /p^="%a%" ^| more ') DO SET "b=%%t"
FOR /f "delims=" %%t IN ('^<NUL SET /p"=%a%" ^| more ') DO SET "b=%%t"
The first one escapes the equal sign. 第一个转义等号。 The second one quotes it.
第二个引用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.