How can you echo a newline in batch files?

2019-01-01 06:12发布

How can you you insert a newline from your batch file output?

I want to do something like:

> echo hello\nworld

Which would output:

hello
world

18条回答
与风俱净
2楼-- · 2019-01-01 06:35

This worked for me, no delayed expansion necessary:

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

It writes output like this:

<html>
<body>
Hello
</body>
</html>
Press any key to continue . . .
查看更多
明月照影归
3楼-- · 2019-01-01 06:35

The most character conservative way to accomplish this in linux systems, is with the -e alias - which interprets escaped characters that are backslashed.

echo -e "hello\nworld"

Here are other examples

查看更多
只若初见
4楼-- · 2019-01-01 06:37

Here you go, create a .bat file with the following in it :

@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

You should see output like the following:

There should be a newline
inserted here.

Press any key to continue . . .

You only need the code between the REM statements, obviously.

查看更多
何处买醉
5楼-- · 2019-01-01 06:38

echo hello & echo.world

This means you could define & echo. as a constant for a newline \n.

查看更多
姐姐魅力值爆表
6楼-- · 2019-01-01 06:39

echo. Enough said.

If you need it in a single line, use the &. For example,

echo Line 1 & echo. & echo line 3

would output as:

Line 1

line 3

Now, say you want something a bit fancier, ...

set n=^&echo.
echo hello %n% world

Outputs

hello
world

Then just throw in a %n% whenever you want a new line in an echo statement. This is more close to your \n used in various languages.

Breakdown

set n= sets the variable n equal to:

^ Nulls out the next symbol to follow:

& Means to do another command on the same line. We don't care about errorlevel(its an echo statement for crying out loud), so no && is needed.

echo. Continues the echo statement.

All of this works because you can actually create variables that are code, and use them inside of other commands. It is sort of like a ghetto function, since batch is not exactly the most advanced of shell scripting languages. This only works because batch's poor usage of variables, not designating between ints, chars, floats, strings, etc naturally.

If you are crafty, you could get this to work with other things. For example, using it to echo a tab

set t=^&echo.     ::there are spaces up to the double colon
查看更多
临风纵饮
7楼-- · 2019-01-01 06:40

To start a new line in batch, all you have to do is add "echo[", like so:

echo Hi!
echo[
echo Hello!
查看更多
登录 后发表回答