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

我想做的事情是:

echo hello\nworld

这将输出:

hello
world

当前回答

简单的

set nl=.
echo hello
echo%nl%
REM without space ^^^
echo World

结果:

hello
world

其他回答

在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

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

可以使用@echo (@echo +[空间]+[不安全空间])

注:不安全空间可用Alt+0160获取

希望能有所帮助。

嗯,你是对的,我需要它在一个Makefile中,它在那里工作得很好。我想我的答案不适合批处理文件…我的坏。

要批量地开始新一行,你所要做的就是添加“echo[”,像这样:

echo Hi!
echo[
echo Hello!

的回声。足够的说。

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

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

Use:

echo hello
echo:
echo world