在Windows批处理中,Linux shell命令echo -n抑制输出末尾的换行符是什么?

其思想是在循环中的同一行上写入。


当前回答

这里是另一个方法,它使用Powershell Write-Host,它有一个-NoNewLine参数,结合start /b,它从批处理中提供了相同的功能。

NoNewLines.cmd

@ECHO OFF
start /b /wait powershell.exe -command "Write-Host -NoNewLine 'Result 1 - ';Write-Host -NoNewLine 'Result 2 - ';Write-Host -NoNewLine 'Result 3 - '"
PAUSE

输出

Result 1 - Result 2 - Result 3 - Press any key to continue . . .

下面这个略有不同,并不完全像OP想要的那样工作,但很有趣,因为每个结果都覆盖了模拟计数器的前一个结果。

@ECHO OFF
start /b /wait powershell.exe -command "Write-Host -NoNewLine 'Result 1 - '"
start /b /wait powershell.exe -command "Write-Host -NoNewLine 'Result 2 - '"
start /b /wait powershell.exe -command "Write-Host -NoNewLine 'Result 3 - '"
start /b /wait powershell.exe -command "Write-Host -NoNewLine 'Result 4 - '"
start /b /wait powershell.exe -command "Write-Host -NoNewLine 'Result 5 - '"
start /b /wait powershell.exe -command "Write-Host -NoNewLine 'Result 6 - '"
start /b /wait powershell.exe -command "Write-Host -NoNewLine 'Result 7 - '"
start /b /wait powershell.exe -command "Write-Host -NoNewLine 'Result 8 - '"
start /b /wait powershell.exe -command "Write-Host -NoNewLine 'Result 9 - '"
PAUSE

其他回答

我相信没有这样的选择。或者你可以试试这个

set text=Hello
set text=%text% world
echo %text%

作为@xmechanix回答的补充,通过将内容写入一个文件,我注意到:

echo | set /p dummyName=Hello World > somefile.txt

这将在打印的字符串的末尾添加一个额外的空格,这可能是不方便的,特别是因为我们试图避免在字符串的末尾添加一个新行(另一个空白字符)。

幸运的是,引用要打印的字符串,即使用:

echo | set /p dummyName="Hello World" > somefile.txt

将打印结尾不带换行符或空格字符的字符串。

Late answer here, but for anyone who needs to write special characters to a single line who find dbenham's answer to be about 80 lines too long and whose scripts may break (perhaps due to user-input) under the limitations of simply using set /p, it's probably easiest to just to pair your .bat or .cmd with a compiled C++ or C-language executable and then just cout or printf the characters. This will also allow you to easily write multiple times to one line if you're showing a sort of progress bar or something using characters, as OP apparently was.

使用Bill Stewart的“Shell脚本工具包”中的EchoX.EXE 如何在Windows Cmd脚本中抑制换行:

@Echo Off
Rem Print three Echos in one line of output
EchoX -n "Part 1 - "
EchoX -n "Part 2 - "
EchoX    "Part 3"
Rem

给:

Part 1 - Part 2 - Part 3
{empty line}
d:\Prompt>

这种用法的帮助是:

Usage: echox [-n] message
  -n       Do not skip to the next line.
  message  The text to be displayed.

该实用程序小于48K,应该位于Path中。它可以做的更多事情:-打印文本而不移动到下一行-打印文本在一定宽度内向左、中间或右边对齐-打印文本与制表符,换行和返回-打印文本在前景和背景颜色

该工具包还包括12个很棒的脚本编写技巧。 下载页面还包含其他三个有用的工具包。

使用set和/p参数可以不带换行符进行回显:

C:\> echo Hello World
Hello World

C:\> echo|set /p="Hello World"
Hello World
C:\>