如何从批处理文件输出中插入换行符?

我想做的事情是:

echo hello\nworld

这将输出:

hello
world

当前回答

就像肯的答案一样,只是用了延迟扩展。

setlocal EnableDelayedExpansion
(set \n=^
%=Do not remove this line=%
)

echo Line1!\n!Line2
echo Works also with quotes "!\n!line2"

First a single linefeed character is created and assigned to the \n-variable. This works as the caret at the line end tries to escape the next character, but if this is a Linefeed it is ignored and the next character is read and escaped (even if this is also a linefeed). Then you need a third linefeed to end the current instruction, else the third line would be appended to the LF-variable. Even batch files have line endings with CR/LF only the LF are important, as the CR's are removed in this phase of the parser.

使用延迟展开的优点是,根本不需要进行特殊的字符处理。 Line1%LF%Line2将失败,因为解析器在单个换行处停止解析。

更多解释见 SO:在Vista/DOS批处理(.bat)文件中,长命令拆分为多行 那么:Windows命令解释器(CMD.EXE)如何解析脚本?

编辑:避免回声。

这并没有回答问题,因为问题是关于单个echo可以输出多行。

但是除了其他答案谁建议使用回声。要创建新行,应注意echo。是最糟糕的,因为它非常慢,它可以完全失败,因为cmd.exe搜索一个名为ECHO的文件,并试图启动它。

如果只打印空行,可以使用其中之一

echo,
echo;
echo(
echo/
echo+
echo=

而是回声的使用。, echo\或echo:应该避免,因为它们会非常慢,这取决于脚本执行的位置,比如网络驱动器。

其他回答

你也可以这样做,

(for %i in (a b "c d") do @echo %~i)

输出将是,

a
b
c d

请注意,当将其放入批处理文件中时,'%'应该加倍。

(for %%i in (a b "c d") do @echo %%~i)

在Ken的回答中添加一个变量,它显示了环境变量的设置值,其中包含新行。

我们使用此方法将错误条件附加到VAR中的字符串中,然后在所有错误检查输出的末尾将所有错误汇总到文件中。

这不是完整的代码,只是一个示例。

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
:: the two blank lines are required!
set NLM=^


set NL=^^^%NLM%%NLM%^%NLM%%NLM%
:: Example Usage:

Set ErrMsg=Start Reporting:
:: some logic here finds an error condition and appends the error report
set ErrMsg=!ErrMsg!!NL!Error Title1!NL!Description!NL!Summary!NL!

:: some logic here finds another error condition and appends the error report
set ErrMsg=!ErrMsg!!NL!Error Title2!NL!Description!NL!Summary!NL!

:: some logic here finds another error condition and appends the error report
set ErrMsg=!ErrMsg!!NL!Error Title3!NL!Description!NL!Summary!NL!

echo %ErrMsg%
pause
echo %ErrMsg% > MyLogFile.log

日志和屏幕输出看起来像这样…

Use:

echo hello
echo:
echo world

请注意,所有解决方案使用光标定位根据控制台虚拟终端序列,光标定位与:

Sequence Code Description Behaviour
ESC [ <n> E CNL Cursor Next Line Cursor down <n> lines from current position

只有在没有到达控制台窗口底部时才能工作。

在底部没有空间来向下移动光标,所以它只是向左移动(与CRLF的CR),之前打印的行从它的开始被覆盖。

的回声。足够的说。

如果需要在单行中使用&。例如,

echo Line 1 & echo. & echo line 3

输出如下:

Line 1

line 3

现在,假设你想要一些更花哨的东西,……

set n=^&echo.
echo hello %n% world

输出

hello
world

然后当你想在echo语句中添加新行时,只需在其中加入%n%。这更接近于你在各种语言中使用的\n。

分解

Set n=设置变量n等于:

^取消后面的下一个符号:

&表示在同一行上执行另一个命令。我们不关心errorlevel(这是一个echo语句),所以不需要&&。

的回声。继续echo语句。

所有这些都是可行的,因为您实际上可以创建代码变量,并在其他命令中使用它们。它有点像贫民区函数,因为批处理并不是最先进的shell脚本语言。这只是因为批处理对变量的使用很差,没有在int、char、float、字符串等之间自然地进行指定。

如果你很狡猾,你可以让它和其他东西一起工作。例如,使用它来回显一个制表符

set t=^&echo.     ::there are spaces up to the double colon