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

我想做的事情是:

echo hello\nworld

这将输出:

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 hello & Echo .world

这意味着您可以定义& echo。作为换行符的常数\n。

有一个标准的功能echo:在cmd/bat-files中写入空行,这模拟了cmd-output中的新行:

@echo off
echo line1
echo:
echo line2

or

@echo line1 & echo: & echo line2

上面引用的cmd-file输出:

line1

line2

在这里,创建一个.bat文件,其中包含以下内容:

@echo off
REM Creating a Newline variable (the two blank lines are required!)
set NLM=^


set NL=^^^%NLM%%NLM%^%NLM%%NLM%
REM Example Usage:
echo There should be a newline%NL%inserted here.

echo.
pause

您应该会看到如下输出:

There should be a newline
inserted here.

Press any key to continue . . .

显然,您只需要REM语句之间的代码。

这对我来说很有效,不需要延迟扩展:

@echo off
(
echo ^<html^> 
echo ^<body^>
echo Hello
echo ^</body^>
echo ^</html^>
)
pause

它像这样写输出:

<html>
<body>
Hello
</body>
</html>
Press any key to continue . . .

Ken和Jeb的解决方案效果很好。

但是新行只生成一个LF字符,我需要CRLF字符(Windows版本)。

为此,在脚本的末尾,我已经将LF转换为CRLF。

例子:

TYPE file.txt | FIND "" /V > file_win.txt
del file.txt
rename file_win.txt file.txt