Перенос строки в cmd windows

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.

Содержание

  • 1 Пробелы в значениях переменных
  • 2 Разрыв строки текста, перенос строки команд
  • 3 Экранирование служебных спецсимволов

Пробелы в значениях переменных

С переменной, в значении которой есть один или несколько пробелов, можно работать как и обычно..

Set PathBase=c:\Program Files\Firefox
Set StartProcess=%PathBase%\Firefox.exe

Но не всегда это работает и в тех случаях, когда по синтаксису пробел не должен находиться в этом месте, тогда используют обрамляющие кавычки

Set PathBase=c:\Program Files\Firefox
echo "%PathBase%\profiles.ini"

Но в некоторых случаях и тот и тот вариант может не подойти, тогда уж наверняка вас выручит иной вариант с кавычками, мой любимый

Set "PathBase=c:\Program Files\Firefox"
echo %PathBase%\profiles.ini

Разрыв строки текста, перенос строки команд

Если текст вашей команды слишком длинный, то это делает сценарий менее наглядным и удобочитаемым. Символ ^ должен быть последним в строке и означает, что следующая строка является продолжением текущей. Возможно разбиение команд более, чем на две строки. Заметим, при печати в консоли на выходе будет все же одна строка. Данный способ применяется только для более удобного восприятия и форматирования длинного кода листинга.

echo ^
Этот способ работает^
не только для текста^
но и для команд

Если нужно сделать перенос печатаемого текста в самой консоли, то просто используется новая команда с новой строки echo ваш текст.
Если нужна пустая строка на выходе, то используйте команду echo с точкой, то есть echo. в консоли выведет пустую строку.

Экранирование служебных спецсимволов

В командном языке Windows существует некоторый набор символов с высоким приоритетом, которые всегда трактуются как спецсимволы. К ним, в частности, относятся:

  • Операторы перенаправления ввода-вывода <, >, >>.
  • Оператор конвейера |.
  • Операторы объединения команд ||, & и &&.
  • Оператор разыменования переменной %…%.

В случае со знаком процента решение довольно хорошо известно и состоит в удвоении этого символа. Для других символов тут нам и придет на помощь уже известный знак домика — символ ^.

:: Это не сработает, вызовет ошибку - > was unexpected at this time.
echo <html>

:: А это сработает
echo ^<html^>

Этим же символом домика можно экранировать и любой другой символ, включая самого себя.

Продолжение следует..

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.

In a Windows Command Prompt (CMD) and PowerShell when you execute the echo command to print some text or redirect it to a file, you can break it into multiple lines.

In Linux you can do this by using the \n.

This short note shows how to break lines and insert new lines using the echo command from the Command Prompt (CMD) and Windows PowerShell.

Cool Tip: Windows grep command equivalent in CMD and PowerShell! Read more →

Windows Command Prompt (CMD)

To insert a line break in the Windows Command Prompt, you can use multiple echo commands as follows:

C:\> (echo Line & echo Newline) > file.txt
C:\> type file.txt
Line
Newline

To print a new line in the Windows Command Prompt, use the echo., for example:

C:\> (echo Line & echo. & echo Newline) > file.txt
C:\> type file.txt
Line

Newline

Windows PowerShell

To insert a line break in the Windows PowerShell, you can use the `n character:

PS C:\> echo "Line`nNewline" > file.txt
PS C:\> type file.txt
Line
Newline

The same `n character can be used to insert a new line in the Windows PowerShell:

PS C:\> echo "Line`n`nNewline" > file.txt
PS C:\> type file.txt
Line

Newline

Was it useful? Share this post with the world!

I’m trying to execute a command on cmd.exe, with a line break or new line as part of the command, like below:

command -option:text  
whatever

But every new line executes the command, instead of continuing the command on the next line.

So how can I input a new line character, or create a multi-line command in cmd.exe?

HopelessN00b's user avatar

HopelessN00b

1,8823 gold badges21 silver badges29 bronze badges

asked Jun 8, 2010 at 9:38

rudimenter's user avatar

2

Use the ^ character as an escape:

command -option:text^ 
whatever

I’m assuming you’re using cmd.exe from Windows XP or later. This is not actual DOS. If you are using actual DOS (MS-DOS, Win3.1, Win95, Win98, WinME), then I don’t believe there is an escape character for newlines. You would need to run a custom shell. cmd.exe will prompt you for More? each time you press enter with a ^ at the end of the line, just press enter again to actually escape/embed a newline.

Wasif's user avatar

Wasif

8,0642 gold badges19 silver badges32 bronze badges

answered Jun 8, 2010 at 9:49

Darth Android's user avatar

Darth AndroidDarth Android

37.9k5 gold badges94 silver badges112 bronze badges

8

Use Alt codes with the numpad

C:\>ver

Microsoft Windows [Version 6.3.9600]

C:\>echo Line1◙Line2 >con
Line1
Line2

C:\>

That line feed character can be entered as an Alt code on the CLI using the numpad: with NumLock on, hold down ALT and type 10 on the numpad before releasing ALT. If you need the CR as well, type them both with Alt+13 and then Alt+10 : ♪◙

Note: this will not work in a batch file.

Sample use case:

You are trying to read the %PATH% or %CLASSPATH% environment variables to get a quick overview of what’s there and in what order — but the wall of text that path returns is unreadable. Then this is something you can quickly type in:

echo %path:;=◙% >con

Edit:

Added the >con workaround that Brent Rittenhouse discovered for newer versions of cmd.exe, where the original method had stopped working.

Community's user avatar

answered Oct 8, 2016 at 1:28

Amit Naidu's user avatar

Amit NaiduAmit Naidu

5497 silver badges10 bronze badges

8

I don’t know if this will work for you but by putting &echo (the following space is important). in between each statement that you want on a new line. I only tried this with a simple bat file of

echo %1

Then saved that as testNewLines.bat

So then the cmd line

testNewLines first line&echo Second Line&echo Third line

Resulted in the following being echoed back

first line
second line
Third line

answered Jun 8, 2010 at 13:10

Haydar's user avatar

HaydarHaydar

1212 bronze badges

^‘s output are saveable.

set br= ^
<</br (newline)>>
<</br>>

Example:

@echo off
setlocal enableExtensions enableDelayedExpansion
rem cd /D "%~dp0"


rem //# need 2 [/br], can't be saved to a var. by using %..%;
set br= ^



set "t=t1!br!t2!br!t3"

for /f "tokens=* delims=" %%q in ("!t!") do (
    echo %%q
)


:scIn
rem endlocal
pause
rem exit /b

; output:

t1
t2
t3
Press any key to continue . . .

Wasif's user avatar

Wasif

8,0642 gold badges19 silver badges32 bronze badges

answered Apr 2, 2019 at 10:10

ilias's user avatar

iliasilias

1314 bronze badges

Expanding on @Amit’s answer (https://superuser.com/a/1132659/955256) I found a way to do it in any font WITHOUT using the legacy console.

All you need to do is simply echo out the line with ALT-10 characters and then redirect it to con and it will work!

For example, given:

(echo New-line detected rigghhhtt ◙^<— HERE!) > CON

edit: Fun fact, it seems that you can put the redirection at the beginning like so:

> CON echo New-line detected rigghhhtt ◙^<— HERE!

Weird, eh?

You will get an output of:


New-line detected rigghhhtt  
<-- HERE!

(The surrounding parenthesis are optional.)

Here is a more robust example of what you can do with this AND carriage returns which now work, and completely independently!:

Best of all, this works if you redirect to a file as well!
(simply change > CON to > desired_output_file.txt

Enjoy!

Wasif's user avatar

Wasif

8,0642 gold badges19 silver badges32 bronze badges

answered Oct 18, 2018 at 18:10

Brent Rittenhouse's user avatar

I believe you can’t do that from the Windows cmd.exe shell. (It is not DOS.)


You do not need a full «custom shell» for that. You will only need to write something like this (example in Python):

import subprocess
subprocess.call(["C:\\bin\\sometool.exe", "test\nwith\nnewlines"])

Or Ruby:

Kernel::exec "C:\\bin\\sometool.exe", "test\nwith\nnewlines"

See, it’s not that hard.

answered Jun 8, 2010 at 12:46

u1686_grawity's user avatar

u1686_grawityu1686_grawity

430k64 gold badges899 silver badges973 bronze badges

Install Powershell Core

Inside your batch file:

MyBatchFile.bat

@echo off
echo Hello
pwsh.exe -Command [System.Console]::WriteLine()
echo world

Wasif's user avatar

Wasif

8,0642 gold badges19 silver badges32 bronze badges

answered May 24, 2020 at 23:10

Joma's user avatar

JomaJoma

1313 bronze badges

1

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

  • Перестал переключаться язык windows 10
  • Перестал работать принтскрин на windows 10
  • Перестает отвечать проводник windows 10
  • Перенос системы с ssd на ssd windows 10 samsung
  • Перестал работать блютуз на ноутбуке windows 10 после обновления