如何从批处理文件输出中插入换行符?
我想做的事情是:
echo hello\nworld
这将输出:
hello
world
如何从批处理文件输出中插入换行符?
我想做的事情是:
echo hello\nworld
这将输出:
hello
world
当前回答
Use:
echo hello
echo:
echo world
其他回答
有一个标准的功能echo:在cmd/bat-files中写入空行,这模拟了cmd-output中的新行:
@echo off
echo line1
echo:
echo line2
or
@echo line1 & echo: & echo line2
上面引用的cmd-file输出:
line1
line2
为什么不使用子字符串/替换空格来echo;?
set "_line=hello world"
echo\%_line: =&echo;%
结果:
hello
world
或者,将\n替换为echo;
set "_line=hello\nworld"
echo\%_line:\n=&echo;%
简单的
set nl=.
echo hello
echo%nl%
REM without space ^^^
echo World
结果:
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:应该避免,因为它们会非常慢,这取决于脚本执行的位置,比如网络驱动器。
Ken和Jeb的解决方案效果很好。
但是新行只生成一个LF字符,我需要CRLF字符(Windows版本)。
为此,在脚本的末尾,我已经将LF转换为CRLF。
例子:
TYPE file.txt | FIND "" /V > file_win.txt
del file.txt
rename file_win.txt file.txt