How can I echo a newline in a batch file?
Asked Answered
C

27

788

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
Citrange answered 25/9, 2008 at 11:50 Comment(8)
Came in useful for me. I had to do echo \n \n | my_app.exe in a script. I did (echo. && echo.) | my_app.exePolycarp
Easy Approach " Code starts :" > echo hello&echo world , will give u what u needPo
You can insert an invisible ascii chr(255) on a separate line which will force a blank new line. Hold down the [alt] key and press 255 on the keypad. this inserts chr(255) which is a blank square. i.e. "echo (alt+255)" You can only use the keypad not the numbers at the top of the querty keyboard!Flynn
Just as half of computer repair is plugging it in and turning it on, half of software development is what I call space engineering. We need our blank lines just so.Encompass
How About This ? echo Yes&echo NoTranquilize
@Flynn thank you for the alt+255 suggestion, works great on the command lineLew
printf "\n\n\n"Rivard
Has anyone here offered newline as an external command batchfile? NEWLINE.bat. Some of the solutions here don't work properly as-is, in a separate batchfile. For example, some syntax will give ECHO is off if called directly from the command-line.Fraxinella
G
539

echo hello & echo.world

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

Grandmother answered 25/9, 2008 at 11:52 Comment(17)
the example doesn't need a period, but you do need one to echo a blank empty line: echo. && echo hello && echo. && echo worldTorbernite
Can you do this with a single echo so it can be redirected to a file?Carangid
@Carangid - $ (echo Hello && echo World) > ./File.txtKopeck
The period thing in "echo." never stops amazing me. It's so dated, and still I always forget that the dot must be strictly concatenated with the command name, with no spaces between. There's no error in the post of yours, I'm writing this just as a reminder: "echo ." != "echo." !Swanhildas
The final answer is missing: $ echo.>>myfile.txt this will add a line break in a fileTchao
Just thought I'd add this. I wanted to view the system PATH variable from the command line, but easily readable. This post helped me, and I came up with this: for /f "tokens=*" %i in ("%path%") do set a=%i && set (b=!a:;=^&echo.!) then echo %b% and voila! Line by line output.Wheelsman
I have more info! echo. makes a new line. echo shows the text instead of 'hello' is not recognized as an internal or external command, operable program or batch file.Upshaw
@NathanJ.Brauer, Single & works too: (echo Hello&echo World) > ./File.txtLati
@mattwilkie, What's the difference between two && instead of one &?Lati
@Lati a single ampersand means "do this, then that" while double means "do this, and if no error then do that". Double pipe, ||, is it's mate, " do this, if failure then do that". See ss64.com/nt/syntax-redirection.htmlTorbernite
@quetzalcoatl, it gets even stranger. Other characters besides dot work too. SS64 says better syntax is echo( for improved performance (still with no space mind you). Extended discussion of other characters and their merits/flaws at ECHO. FAILS to give text or blank line - Instead use ECHO/Torbernite
@mattwilkie, Continue at the comments in the answer below....Lati
@mattwilkie - technically, "do this, then that" would be using a single semicolon (e.g. echo hi; echo bye;). Using a single ampersand can have the same result, but it would combine the two return values into one collective binary value rather than having two separate, independent return values (it's more complicated than this, but this is the beginning of the basics haha).Kopeck
@NathanJ.Brauer, this Command/CMD (Dos/Windows) not bash etc. Semicolon is just another character and doesn't have any effect.Torbernite
Note that the space between hello and the & is echoed too! Just remove it to avoid that...Normandnormandy
@Swanhildas wow, it's like punctuation matters in programming. Those darn spaces.Fraxinella
@mattwilkie SS64 recommends echo: now.Vesical
I
690

Use:

echo hello
echo:
echo world
Inexpiable answered 25/9, 2008 at 11:51 Comment(11)
Is it possible while providing a string within a single echo statement?Citrange
Why do you need to do it with a single echo statement; where's the harm in having another?Pros
@Rob, I just came across this problem and none of these work. You need to echo in a single statement in my example. I am generating some tex files from HTML and generating a Makefile by using echo "Makefile contents (which has \n)" > Makefile With multiple echos, it wouldn't workCarangid
@Rob, Of course we need a single statement..... How would you pipe the 3 echos to a file then?Lati
@Rob, can't you just answer Brian R, Bondy's question? He doesn't ask for alternative approachesDisini
Use echo; instead of echo.. For some reason, echo. will not work in the case that the working directory happens to have a file called echo in it already. However, echo; works fine.Carlyle
Use & (or &&) to do them in a single statement: For example, to put "hello\nworld" in a txt file: (echo hello & echo world) >> ./test.txtWrongdoing
For multi-line output to a file why not just do the following? echo line 1 > Makefile and then echo line 2 >> Makefile . Use of >> causes the output to be appended to the file, which is precisely the behavior you need for this case.Justicz
echo: is recommended by SS64.Rupee
If anybody ever wondered how this trick works, here is how. ^ or : characters in echo command can be used to escape command characters like & < > | ON OFF, so by using : we are basically escaping the newline! Seems very hacky, but it works! It also works with text files like this echo:>>foo.txtShakespeare
This doesn't work for me. I get an extra blank line. I just want a line return.Kathie
G
539

echo hello & echo.world

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

Grandmother answered 25/9, 2008 at 11:52 Comment(17)
the example doesn't need a period, but you do need one to echo a blank empty line: echo. && echo hello && echo. && echo worldTorbernite
Can you do this with a single echo so it can be redirected to a file?Carangid
@Carangid - $ (echo Hello && echo World) > ./File.txtKopeck
The period thing in "echo." never stops amazing me. It's so dated, and still I always forget that the dot must be strictly concatenated with the command name, with no spaces between. There's no error in the post of yours, I'm writing this just as a reminder: "echo ." != "echo." !Swanhildas
The final answer is missing: $ echo.>>myfile.txt this will add a line break in a fileTchao
Just thought I'd add this. I wanted to view the system PATH variable from the command line, but easily readable. This post helped me, and I came up with this: for /f "tokens=*" %i in ("%path%") do set a=%i && set (b=!a:;=^&echo.!) then echo %b% and voila! Line by line output.Wheelsman
I have more info! echo. makes a new line. echo shows the text instead of 'hello' is not recognized as an internal or external command, operable program or batch file.Upshaw
@NathanJ.Brauer, Single & works too: (echo Hello&echo World) > ./File.txtLati
@mattwilkie, What's the difference between two && instead of one &?Lati
@Lati a single ampersand means "do this, then that" while double means "do this, and if no error then do that". Double pipe, ||, is it's mate, " do this, if failure then do that". See ss64.com/nt/syntax-redirection.htmlTorbernite
@quetzalcoatl, it gets even stranger. Other characters besides dot work too. SS64 says better syntax is echo( for improved performance (still with no space mind you). Extended discussion of other characters and their merits/flaws at ECHO. FAILS to give text or blank line - Instead use ECHO/Torbernite
@mattwilkie, Continue at the comments in the answer below....Lati
@mattwilkie - technically, "do this, then that" would be using a single semicolon (e.g. echo hi; echo bye;). Using a single ampersand can have the same result, but it would combine the two return values into one collective binary value rather than having two separate, independent return values (it's more complicated than this, but this is the beginning of the basics haha).Kopeck
@NathanJ.Brauer, this Command/CMD (Dos/Windows) not bash etc. Semicolon is just another character and doesn't have any effect.Torbernite
Note that the space between hello and the & is echoed too! Just remove it to avoid that...Normandnormandy
@Swanhildas wow, it's like punctuation matters in programming. Those darn spaces.Fraxinella
@mattwilkie SS64 recommends echo: now.Vesical
B
161

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.

Battology answered 6/11, 2008 at 18:43 Comment(12)
Very impressive, could you take time to explain how the line set NL=^^^%NLM%%NLM%^%NLM%%NLM% works? I can't quite get my head round itFloriated
Alas, this doesn't work when passing the echoed string to another program.Highness
@andy methinks a +8 comment warrants a question: #6380119Torbernite
This is a wonderful example to show that cmd.exe and Windows batch files are totally insane!Benzofuran
NOTE TO SELF: The line "set NLM=^" must have nothing after the CARET and must have 2 blank lines after it.Honeyed
Unfortunately you cannot use it in a variable. For example, set z=foo%NL%bar & echo %z% will not give the expected results, it will only print foo.Fictional
See my answer for a simpler method. set nl=^&echo., then just echo hello %nl% world yields the same effect.Bartholomeo
I'm getting "There should be a newlineinserted here."Dresden
@Fictional You can indeed put a linebreak in a variable, using the first form. Try this out: set A=first line^^^%NLM%%NLM%^%NLM%%NLM%second line then echo %A%Mcandrew
@rkagerer, it works. Nice! 👍 (Too bad the command-line's escaping methods are so insane. :-)Fictional
It will work for SET variables if you use DelayedExpansion and !! instead of %%. For example, set ErrMsg=!NL!Error Title1!NL!Description!NL!Summary!NL!Orientate
echo. is the trick!Denman
T
121

There is a standard feature echo: in cmd/bat-files to write blank line, which emulates a new line in your cmd-output:

@echo off
echo line1
echo:
echo line2

or

@echo line1 & echo: & echo line2

Output of cited above cmd-file:

line1

line2
Teresa answered 26/6, 2010 at 8:11 Comment(13)
In fact, any UNUSED special char should work. I always encourage the use of / because the slash is the standard char for command options. Also, I always criticize the use of the dot that somebody in Microsoft unfortunately choose because the command: echo.com give different results depending on the version of MS-DOS/Windows Batch command processor.Ledbetter
The only version that always works is echo(. It looks like it could cause problems, but it actually works perfectly. All other forms have at least one situation where the command will not perform as desired.Manager
@Ledbetter could you find some reference for this? I tested and it works which is fascinating but there must exist some designer memo, specification or at least manual that tells this story.Somewhat
@Manager this is even more fascinating. do you know about examples or explanation about the situations you speak of? also, do you know about any designer story, memo, specification or manual that describes this feature of the dos and cmd command line?Somewhat
@naxa - Nothing official, just collective knowledge derived by a few batch hackers. The goal is to have syntax that can be used to ECHO any value, including nothing, and never have to worry about getting anything other than what is expected. The best summary I know of is at dostips.com/forum/viewtopic.php?p=4554#p4554. It kind of leaves you hanging, but no one has ever come up with a scenario where ECHO( fails.Manager
@dbenham, The claim that echo( is the only version which works is incorrect. The author rules against ., +, [, and ], but there is still "echo=", "echo,", "echo\ ", "echo/ " and "echo:" which he didn't address at all.Lati
@Aacini, Why not echo=? Using / is misleading because / already has a meaning in cmd (used for representing flags).Lati
@Pacerier: try echo=/? and echo,/? and you will see that both fails (because they do not show "/?"). From the remaining three, echo\/? looks like an "escape" in other languages, and echo:/? may be mistaken for a label or drive. The form that looks "more standard" is echo//? precisely because / is used for command options!Ledbetter
@Lati - there are examples of failure for each of those suggestions. Carefully read dostips.com/forum/viewtopic.php?p=4554#p4554.Manager
@Lati there is enough echo going on here for a standalone question. Perhaps something along the lines of "what characters can immediately follow echo, and what are their effects?"Torbernite
Can confirm echo( seems arbitrarily safe, even in deeply nested FOR loops which can be notorious for special-character weirdness handling.Boomkin
@Manager when I use echo( it is not creating a newline, but rather this ഠ嘊攀爀猀椀漀渀                    ഀ਀ 㤀㘀䌀㄀     㐀 㔀䘀   㔀㄀㘀㘀 ㄀㠀   ഀ਀.Attenuator
@CardinalSystem Was this with a Chinese Windows? Or on a PC fabricated in China? Or perhaps hacked by a Samurai? :)Vesical
O
87

Like the answer of Ken, but with the use of the delayed expansion.

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.

The advantage of using the delayed expansion is, that there is no special character handling at all.
echo Line1%LF%Line2 would fail, as the parser stops parsing at single linefeeds.

More explanations are at
SO:Long commands split over multiple lines in Vista/DOS batch (.bat) file
SO:How does the Windows Command Interpreter (CMD.EXE) parse scripts?

Edit: Avoid echo.

This doesn't answer the question, as the question was about single echo that can output multiple lines.

But despite the other answers who suggests the use of echo. to create a new line, it should be noted that echo. is the worst, as it's very slow and it can completly fail, as cmd.exe searches for a file named ECHO and try to start it.

For printing just an empty line, you could use one of

echo,
echo;
echo(
echo/
echo+
echo=

But the use of echo., echo\ or echo: should be avoided, as they can be really slow, depending of the location where the script will be executed, like a network drive.

O answered 16/6, 2011 at 23:52 Comment(8)
If you will be passing the string with newlines as a parameter to a batch subroutine, e.g. call :pause line1!\n!line2, start the subroutine with setlocal EnableDelayedExpansion and end it with setlocal DisableDelayedExpansion to keep the newlines from being interpreted prematurely.Saponaceous
+1 for the cast of characters echo, echo; echo( echo/ echo+ echo= and the rogues gallery echo. echo\ echo:. Now if you were to explain why in holy heck these work, I'd owe you a free beer.Encompass
Can you put the newline into a NEWLINE.bat script by itself?Fraxinella
@johnywhy Yes, move the code into the newline.bat probably with an echo(!\n!O
@O You're saying i have to use an open-paren when i use it from a .bat file? Where does the close-paren go? echo(!\n! My intention is to have call an external setup_newline.bat at the top of every batch file which wants to use your method. Or, even better, just put newline where ever i need a newline, and have that newline call newline.bat which returns !\n!Fraxinella
@johnywhy Better ask a new question, the comments are a bit small for longer descriptionsO
@O Thx, i might! Plz consider adding this to your answer here.Fraxinella
This. Awesome sauce. Elegant. Effective.Pulchritudinous
B
46

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
Bartholomeo answered 16/7, 2014 at 23:50 Comment(2)
Do not use echo. as it first attempts to find a file by that name. Use other punctuation, such as echo,Subjugate
Fails with echo %n%hello%n%worldecho & echo:hello & echo:world, of course.Vesical
A
19

When echoing something to redirect to a file, multiple echo commands will not work. I think maybe the ">>" redirector is a good choice:

echo hello > temp
echo world >> temp
Antioch answered 9/8, 2009 at 1:0 Comment(2)
The first example, using ">", will create a new file, the second one, using ">>", will append to an existing file (or create it if it doesn't already exist).Uncommitted
(echo hello && echo world) > temp mentioned by Nathan J. Brauer in a comment to the (current) accepted answer works.Vesical
C
18

If you need to put results to a file, you can use:

(echo a & echo: & echo b) > file_containing_multiple_lines.txt
Clothesline answered 2/9, 2014 at 0:9 Comment(0)
D
14

Just like Grimtron suggests - here is a quick example to define it:

@echo off
set newline=^& echo.
echo hello %newline%world

Output

C:\>test.bat
hello
world
Decay answered 5/3, 2010 at 16:47 Comment(6)
It will actually echo an additional newline after "world"Fidole
@blue the trailing newline seems to be function of the batch file itself. If you repeat the echo hello %newline%world line there are no spaces between.Torbernite
echo "Hello %newline% world" fails as it is inside of quotes. Because it isn't a real newline.O
i see this everywhere and it's misleading/confusing, and of course, horribly inefficient compared to the real newline version.Lepage
@HaxAddict1337 Which is the "real newline version"?Fraxinella
Fails with echo %newline%hello%newline%worldecho & echo:hello & echo:world, of course.Vesical
Z
9

You can also do like this,

(for %i in (a b "c d") do @echo %~i)

The output will be,

a
b
c d

Note that when this is put in a batch file, '%' shall be doubled.

(for %%i in (a b "c d") do @echo %%~i)
Zosema answered 20/9, 2011 at 17:6 Comment(3)
This solution also works if you want to echo an ampersand & instead of a newline.Enameling
i think i found a bug: the * charDarlenedarline
This is an unnecessarily complicated echo a & echo b & echo c d and doesn't answer the question with echo a sentence that contains\na newline identifier in it. Of course, one could write for %%i in ("a sentence that contains" "a newline in it") do @echo %%~i, but really?Vesical
S
8

If anybody comes here because they are looking to echo a blank line from a MINGW make makefile, I used

@cmd /c echo.

simply using echo. causes the dreaded process_begin: CreateProcess(NULL, echo., ...) failed. error message.

I hope this helps at least one other person out there :)

Shantel answered 22/4, 2013 at 4:56 Comment(2)
Not sure if sarcasm or not :PShantel
Find out by looking in your inbox :DTrunks
M
6

To echo a newline, add a dot . right after the echo:

echo.
Maupassant answered 19/1, 2023 at 18:27 Comment(1)
Adding an answer to a 15 years old question should contain anything new, but your answer is already given multiple times here before. Btw. echo. isn't a good answer, because it has drawbacksO
V
4

After a sleepless night and after reading all answers herein, after reading a lot of SS64 > CMD and after a lot of try & error I found:

The (almost) Ultimate Solution

TL;DR

... for early adopters.

Important!
Use a text editor for C&P that supports Unicode, e.g. Notepad++!

Set Newline Environment Variable ...

... in the Current CMD Session

Important!
Do not edit anything between '=' and '^'! (There's a character in between though you don't see it. Neither here nor in edit mode. C&P works here.)
:: Sets newline variables in the current CMD session
set \n=​^&echo(
set nl=​^&echo(

... for the Current User

Important!
Do not edit anything between (the second) '' and '^'! (There's a character in between though you don't see it. Neither here nor in edit mode. C&P works here.)
:: Sets newline variables for the current user [HKEY_CURRENT_USER\Environment]
setx \n ​^&echo(
setx nl ​^&echo(

... for the Local Machine

Important!
Do not edit anything between (the second) '' and '^'! (There's a character in between though you don't see it. Neither here nor in edit mode. C&P works here.)
:: Sets newline variables for the local machine [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]
setx \n ​^&echo( /m 
setx nl ​^&echo( /m 

Why just almost?

It does not work with double-quotes that are not paired (opened and closed) in the same printed line, except if the only unpaired double-quote is the last character of the text, e.g.:

  • works: ""echo %\n%...after "newline". Before "newline"...%\n%...after "newline" (paired in each printed line)

  • works: echo %\n%...after newline. Before newline...%\n%...after newline" (the only unpaired double-quote is the last character)

  • doesn't work: echo "%\n%...after newline. Before newline...%\n%...after newline" (double-quotes are not paired in the same printed line)

    Workaround for completely double-quoted texts (inspired by Windows batch: echo without new line):

    set BEGIN_QUOTE=echo ^| set /p !="""
    ...
    %BEGIN_QUOTE%
    echo %\n%...after newline. Before newline...%\n%...after newline"
    

It works with completely single-quoted texts like:

echo '%\n%...after newline. Before newline...%\n%...after newline'

Added value: Escape Character

Note
There's a character after the '=' but you don't see it here but in edit mode. C&P works here.
:: Escape character - useful for color codes when 'echo'ing
:: See https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#text-formatting
set ESC=

For the colors see also https://i.stack.imgur.com/9SkGq.jpg and https://gist.github.com/gerib/f2562474e7ca0d3cda600366ee4b8a45.

2nd added value: Getting Unicode characters easily

A great page for getting 87,461 Unicode characters (AToW) by keyword(s): https://www.amp-what.com/.

The Reasons

  • The version in Ken's answer works apparently (I didn't try it), but is somehow...well...you see:

    set NLM=^
    
    
    set NL=^^^%NLM%%NLM%^%NLM%%NLM%
    
  • The version derived from user2605194's and user287293's answer (without anything between '=' and '^'):

    set nl=^&echo(
    set \n=^&echo(
    

    works partly but fails with the variable at the beginning of the line to be echoed:

    > echo %\n%Hello%\n%World!
    echo   & echo(Hello & echo(World!
    echo is ON.
    Hello
    World
    

    due to the blank argument to the first echo.

  • All others are more or less invoking three echos explicitely.

  • I like short one-liners.

The Story Behind

To prevent set \n=^&echo: suggested in answers herein echoing blank (and such printing its status) I first remembered the Alt+255 user from the times when Novell was a widely used network and code pages like 437 and 850 were used. But 0d255/0xFF is ›Ÿ‹ (Latin Small Letter Y with diaeresis) in Unicode nowadays.

Then I remembered that there are more spaces in Unicode than the ordinary 0d32/0x20 but all of them are considered whitespaces and lead to the same behaviour as ›␣‹.

But there are even more: the zero width spaces and joiners which are not considered as whitespaces. The problem with them is, that you cannot C&P them since with their zero width there's nothing to select. So, I copied one that is close to one of them, the hair space (U+200A) which is right before the zero width space (U+200B) into Notepad++, opened its Hex-Editor plugin, found its bit representation E2 80 8A and changed it to E2 80 8B. Success! I had a non-whitespace character that's not visible in my \n environment variable.

Vesical answered 26/11, 2021 at 9:16 Comment(5)
on standard codepage 437 this line: echo Hello%\n%world will echo HelloΓÇï <newline> World but works when doing chcp 65001Jacquelyn
@Jacquelyn No wonder, CP 437 is no Unicode codepage. I saw the same on Windows 7. Which standard? Windows 7 and prior to that? Unicode is 30(!) years old now. I think it can, even should be considered as standard now.Vesical
The code page in my region on a newly installed windows 10 pro system is 437.Jacquelyn
@Jacquelyn Yes, MS ignored Unicode in their OSs for decades. Since Win 8 I work with them only if I must.Vesical
set \n=​^&echo: is only a weak hack, it isn't a newline definition. Or try set multiline=Line1%\n%Line2 and then echo ### !multiline!. The answer from Ken should be used or the delayed expansion variant of it.O
E
3

Ken and Jeb solutions works well.

But the new lines are generated with only an LF character and I need CRLF characters (Windows version).

To this, at the end of the script, I have converted LF to CRLF.

Example:

TYPE file.txt | FIND "" /V > file_win.txt
del file.txt
rename file_win.txt file.txt
Elbaelbart answered 30/9, 2016 at 15:24 Comment(0)
C
3

If one needs to use famous \n in string literals that can be passed to a variable, may write a code like in the Hello.bat script below:

@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!%

This way multiline output may by prepared in one place, even in other scritpt or external file, and printed in another.

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).

Above example may be refined to a subroutine or standalone batch, used like call:mlecho Hi\nI'm your comuter:

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


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

Please note, that additional backslash won't prevent the script from parsing \n substring.

Cockatiel answered 8/2, 2018 at 9:51 Comment(4)
You are essentially doing the same thing as Jeb's answer above.Schmooze
Answers I read above were very helpful but I needed to call a script od subroutine which will parse \n so I'd avoid implementing the trick everywhere. This needed to refine a solution and I shared this refinement. Hope it didn't harm any animal.Cockatiel
This answer is useful, but since exclamation marks are interpreted, how can your argument display a litteral exclamation mark? I tried escaping them by prefixing one or two carets, but it did not work.Sandry
@FlorentAngly, try this: set ex=! setlocal enableDelayedExpansion echo shout!ex!Cockatiel
G
2

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

echo Hi!
echo[
echo Hello!
Genuflect answered 16/12, 2016 at 20:31 Comment(5)
It's slow and it fails when a file exists with the name echo[.batO
What? It should work instantly, and also just delete the echo[.bat file.Genuflect
It is pretty much the exact same thing as echo. syntax.Genuflect
Yes and echo. is a bad solution, too.O
As can be seen in previous answers, this will try to locate a file on the path first, which causes it to be so slow. Same is true for echo.. Expecting users of your script to delete files on their system just because your script needs a newline doesn't sound like good design to me.Fixer
C
2

why not use substring/replace space to echo;?

set "_line=hello world"
echo\%_line: =&echo;%
  • Results:
hello
world
  • Or, replace \n to echo;
set "_line=hello\nworld"
echo\%_line:\n=&echo;%
Coat answered 5/10, 2020 at 12:3 Comment(4)
While this may work (I didn't test it) it's rather inconvenient to assign your (potentially many) texts to an env var and perform a string replacement every time.Vesical
@GeroldBroser ok, how about testing and seeing what can be commented if it doesn't work?Coat
@GeroldBroser About what is and is not inconvenient. This depends on each one and their needs, capacity and knowledge, I can assign variations, substitutions, and several substrings in many env var without necessarily writing each one of them.Coat
why hasn't anyone commented this before? Which answer does not bring you equal concerns?Coat
S
2

For windows 10 with virtual terminal sequences there exists the means control the cursor position to a high degree.

To define the escape sequence 0x1b, the following can be used:

@Echo off
 For /f %%a in ('echo prompt $E^| cmd')Do set \E=%%a

To output a single newline Between Strings:

<nul set /p "=Hello%\E%[EWorld"

To output n newlines where n is replaced with an integer:

<nul set /p "=%\E%[nE"

Many

Schnapp answered 7/6, 2021 at 17:49 Comment(1)
See my comment to @Vopel's answer herein with the resume that ESC [ <n> E (Cursor Next Line – Cursor down <n> lines from current position) only works unless you haven't reached the bottom of the console window.Vesical
V
2

Please note that all solutions that use cursor positioning according to Console Virtual Terminal Sequences, Cursor Positioning with:

Sequence Code Description Behaviour
ESC [ <n> E CNL Cursor Next Line Cursor down <n> lines from current position

only work as long as the bottom of the console window is not reached.

At the bottom there is no space left to move the cursor down so it just moves left (with the CR of CRLF) and the line printed before is overwritten from its beginning.

Vesical answered 26/11, 2021 at 3:44 Comment(0)
H
1

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 . . .
Hiro answered 2/6, 2010 at 15:35 Comment(2)
-1 echo asdf >myfile.txt will produce the exact same results. echo appends a newline to the end of the string.Fidole
Great answer, being the only person who recognized the value of using the parenthesis for new lines. I believe this is how the makers of DOS intended you to do it.Ibarra
D
1

14 years later I recommend to use Powershell instead.

You can even most probably just change the file ending from .bat to .ps1 and have it working.

Then, you can use

echo "Hello`nWorld"

# or even

echo Hello`nWorld

Tested on Win10.

You can also do Windows-type newlines with echo "Hello`r`nWorld".

Source: https://devblogs.microsoft.com/scripting/powertip-new-lines-with-powershell/, it says "Use the `n character".


A lot of confusion within the other answers and comments was due to echo being available on Windows and Linux. For linux, you can simply use echo "Hello\nWorld" to get the same result on most distros.

But still, it's recommended to use printf in linux scripts.

Droughty answered 14/5, 2023 at 10:15 Comment(1)
It makes no sense to switch the language to solve a minor problemO
R
0

You can use @echo ( @echo + [space] + [insecable space] )

Note: The insecable space can be obtained with Alt+0160

Hope it helps :)

[edit] Hmm you're right, I needed it in a Makefile, it works perfectly in there. I guess my answer is not adapted for batch files... My bad.

Rhody answered 18/7, 2013 at 13:22 Comment(2)
I got ECHO ist eingeschaltet (ON). not an empty line, tried at the cmd-promptO
That’s a non-breaking space, not a newline.Rey
B
0

simple

set nl=.
echo hello
echo%nl%
REM without space ^^^
echo World

Result:

hello
world
Bloodshed answered 30/4, 2021 at 4:4 Comment(1)
Where is the difference to this 13 years old answer? Your answer is complex without necessity. And like the other solution, it doesn't answer the question how to do it with a single echoO
T
0

Be aware, this won't work in console because it'll simulate an escape key and clear the line.

Using this code, replace <ESC> with the 0x1b escape character or use this Pastebin link:

:: 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!
Trombley answered 31/10, 2021 at 19:19 Comment(2)
This works as long as your command line doesn't reach the bottom of the console window! Then just world! is displayed since at the bottom there is no space left to move the cursor down so it just moves left (with the CR of CRLF) and overwrites Hello . Proof: With echo Hello my%\n%world! world!my is displayed. Anyway, for reference: Console Virtual Terminal Sequences, Cursor Positioning.Vesical
Damn, you're right. That's disappointing.Trombley
O
0

Adding a variant to Ken's answer, that shows setting values for environment variables with new lines in them.

We use this method to append error conditions to a string in a VAR, then at the end of all the error checking output to a file as a summary of all the errors.

This is not complete code, just an example.

@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

Log and Screen output look like this...

Log output of the script

Screen output of the script

Orientate answered 31/1, 2022 at 21:34 Comment(1)
If you use delayed expansion, I can't see any reason to still use percent expansion with line feeds. With delayed expansion you only need a simple definition for the NL and the echo of variables is simple, too.O
Z
0

You can use printf instead of echo:

printf "hello\nworld"

Output:

hello
world
Zincography answered 27/4, 2023 at 7:43 Comment(3)
printf is not a valid cmd/batch command.Eldoree
It is valid for me !!Zincography
printf works on linux, but the question got the Windows tag.Droughty
P
0

To write this to a file, the only good option I found is. Unfortunately I had difficulties to get this in a if (in case you get troubles as well, of course I used setlocal EnableDelayedExpansion)

set text=hello\nworld
set "text=%text:\n= & echo %"
(echo %text%) > file.txt
cat file.txt
Pencel answered 5/11, 2023 at 10:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.