如何从批处理文件输出中插入换行符?
我想做的事情是:
echo hello\nworld
这将输出:
hello
world
如何从批处理文件输出中插入换行符?
我想做的事情是:
echo hello\nworld
这将输出:
hello
world
当前回答
Use:
echo hello
echo:
echo world
其他回答
可以使用@echo (@echo +[空间]+[不安全空间])
注:不安全空间可用Alt+0160获取
希望能有所帮助。
嗯,你是对的,我需要它在一个Makefile中,它在那里工作得很好。我想我的答案不适合批处理文件…我的坏。
有一个标准的功能echo:在cmd/bat-files中写入空行,这模拟了cmd-output中的新行:
@echo off
echo line1
echo:
echo line2
or
@echo line1 & echo: & echo line2
上面引用的cmd-file输出:
line1
line2
要批量地开始新一行,你所要做的就是添加“echo[”,像这样:
echo Hi!
echo[
echo Hello!
在这里,创建一个.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语句之间的代码。
如果需要在可以传递给变量的字符串中使用著名的\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子字符串。