如何从批处理文件输出中插入换行符?
我想做的事情是:
echo hello\nworld
这将输出:
hello
world
如何从批处理文件输出中插入换行符?
我想做的事情是:
echo hello\nworld
这将输出:
hello
world
当前回答
在这里,创建一个.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语句之间的代码。
其他回答
Ken和Jeb的解决方案效果很好。
但是新行只生成一个LF字符,我需要CRLF字符(Windows版本)。
为此,在脚本的末尾,我已经将LF转换为CRLF。
例子:
TYPE file.txt | FIND "" /V > file_win.txt
del file.txt
rename file_win.txt file.txt
的回声。足够的说。
如果需要在单行中使用&。例如,
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的回答中添加一个变量,它显示了环境变量的设置值,其中包含新行。
我们使用此方法将错误条件附加到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
日志和屏幕输出看起来像这样…
就像Grimtron建议的那样-这里有一个简单的例子来定义它:
@echo off
set newline=^& echo.
echo hello %newline%world
输出
C:\>test.bat
hello
world
要回显换行符,请添加一个点。就在回声之后:
echo.