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

我想做的事情是:

echo hello\nworld

这将输出:

hello
world

当前回答

的回声。足够的说。

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

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

其他回答

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

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

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

例子:

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

如果需要在可以传递给变量的字符串中使用著名的\n,可以编写如下Hello.bat脚本所示的代码:

@echo off
set input=%1
if defined input (
    set answer=Hi!\nWhy did you call me a %input%?
) else (
    set answer=Hi!\nHow are you?\nWe are friends, you know?\nYou can call me by name.
)

setlocal enableDelayedExpansion
set newline=^


rem Two empty lines above are essential
echo %answer:\n=!newline!%

通过这种方式,多行输出可以在一个地方准备,甚至在其他脚本或外部文件中,并在另一个地方打印。

The line break is held in newline variable. Its value must be substituted after the echo line is expanded so I use setlocal enableDelayedExpansion to enable exclamation signs which expand variables on execution. And the execution substitutes \n with newline contents (look for syntax at help set). We could of course use !newline! while setting the answer but \n is more convenient. It may be passed from outside (try Hello R2\nD2), where nobody knows the name of variable holding the line break (Yes, Hello C3!newline!P0 works the same way).

上面的例子可以细化为子程序或独立批处理,如调用:mlecho Hi\ i 'm your computer:

:mlecho
setlocal enableDelayedExpansion
set text=%*
set nl=^


echo %text:\n=!nl!%
goto:eof

请注意,额外的反斜杠不会阻止脚本解析\n子字符串。

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

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

它像这样写输出:

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

注意,这不会在控制台工作,因为它将模拟一个escape键和清除行。

使用这段代码,将<ESC>替换为0x1b转义字符或使用这个Pastebin链接:

:: Replace <ESC> with the 0x1b escape character or copy from this Pastebin:
:: https://pastebin.com/xLWKTQZQ

echo Hello<ESC>[Eworld!

:: OR

set "\n=<ESC>[E"
echo Hello%\n%world!

如果你需要把结果放到一个文件中,你可以使用:

(echo a & echo: & echo b) > file_containing_multiple_lines.txt