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_USEREnvironment]
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_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment]
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://imgur.com/a/EuNXEar 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
echo
ed:> 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
echo
s 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 FilesFirefox Set StartProcess=%PathBase%Firefox.exe
Но не всегда это работает и в тех случаях, когда по синтаксису пробел не должен находиться в этом месте, тогда используют обрамляющие кавычки
Set PathBase=c:Program FilesFirefox echo "%PathBase%profiles.ini"
Но в некоторых случаях и тот и тот вариант может не подойти, тогда уж наверняка вас выручит иной вариант с кавычками, мой любимый
Set "PathBase=c:Program FilesFirefox" echo %PathBase%profiles.ini
Разрыв строки текста, перенос строки команд
Если текст вашей команды слишком длинный, то это делает сценарий менее наглядным и удобочитаемым. Символ ^ должен быть последним в строке и означает, что следующая строка является продолжением текущей. Возможно разбиение команд более, чем на две строки. Заметим, при печати в консоли на выходе будет все же одна строка. Данный способ применяется только для более удобного восприятия и форматирования длинного кода листинга.
echo ^ Этот способ работает^ не только для текста^ но и для команд
Если нужно сделать перенос печатаемого текста в самой консоли, то просто используется новая команда с новой строки echo ваш текст.
Если нужна пустая строка на выходе, то используйте команду echo с точкой, то есть echo. в консоли выведет пустую строку.
Экранирование служебных спецсимволов
В командном языке Windows существует некоторый набор символов с высоким приоритетом, которые всегда трактуются как спецсимволы. К ним, в частности, относятся:
- Операторы перенаправления ввода-вывода <, >, >>.
- Оператор конвейера |.
- Операторы объединения команд ||, & и &&.
- Оператор разыменования переменной %…%.
В случае со знаком процента решение довольно хорошо известно и состоит в удвоении этого символа. Для других символов тут нам и придет на помощь уже известный знак домика — символ ^.
:: Это не сработает, вызовет ошибку - > was unexpected at this time. echo <html> :: А это сработает echo ^<html^>
Этим же символом домика можно экранировать и любой другой символ, включая самого себя.
Продолжение следует..
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
1,8843 gold badges21 silver badges29 bronze badges
asked Jun 8, 2010 at 9:38
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
7,6032 gold badges15 silver badges32 bronze badges
answered Jun 8, 2010 at 9:49
Darth AndroidDarth Android
37.5k5 gold badges94 silver badges111 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.
answered Oct 8, 2016 at 1:28
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
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
7,6032 gold badges15 silver badges32 bronze badges
answered Apr 2, 2019 at 10:10
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
7,6032 gold badges15 silver badges32 bronze badges
answered Oct 18, 2018 at 18:10
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", "testnwithnnewlines"])
Or Ruby:
Kernel::exec "C:\bin\sometool.exe", "testnwithnnewlines"
See, it’s not that hard.
answered Jun 8, 2010 at 12:46
user1686user1686
401k59 gold badges845 silver badges915 bronze badges
Install Powershell Core
Inside your batch file:
MyBatchFile.bat
@echo off
echo Hello
pwsh.exe -Command [System.Console]::WriteLine()
echo world
Wasif
7,6032 gold badges15 silver badges32 bronze badges
answered May 24, 2020 at 23:10
JomaJoma
1313 bronze badges
1
195 / 34 / 3 Регистрация: 12.05.2010 Сообщений: 361 |
|
1 |
|
Есть ли специальный символ для перехода на новую строку?03.06.2010, 14:55. Показов 46189. Ответов 9
Люди есть ли такой знак только испольняющей кнопки [Enter] ???
0 |
Почетный модератор 28037 / 15768 / 981 Регистрация: 15.09.2009 Сообщений: 67,753 Записей в блоге: 78 |
|
03.06.2010, 14:57 |
2 |
а что нужно сделать то?
0 |
195 / 34 / 3 Регистрация: 12.05.2010 Сообщений: 361 |
|
03.06.2010, 18:21 [ТС] |
3 |
просто нужно Добавлено через 3 минуты Копарация Microsoft вопрос есть ли такой спец знак ?
0 |
Почетный модератор 28037 / 15768 / 981 Регистрация: 15.09.2009 Сообщений: 67,753 Записей в блоге: 78 |
|
03.06.2010, 23:30 |
4 |
echo Копарация Microsoft
1 |
195 / 34 / 3 Регистрация: 12.05.2010 Сообщений: 361 |
|
04.06.2010, 15:39 [ТС] |
5 |
я это знаю !!!!
0 |
Почетный модератор 28037 / 15768 / 981 Регистрация: 15.09.2009 Сообщений: 67,753 Записей в блоге: 78 |
|
04.06.2010, 17:46 |
6 |
я про такой не вкурсе,
0 |
12383 / 7222 / 758 Регистрация: 09.09.2009 Сообщений: 28,183 |
|
05.06.2010, 00:34 |
7 |
esc 13 или 14 — не помню точно
0 |
195 / 34 / 3 Регистрация: 12.05.2010 Сообщений: 361 |
|
07.06.2010, 21:48 [ТС] |
8 |
esc 13 или 14 — не помню точно Чего??? Esc + 13 или 14 ?
0 |
ComSpec 3455 / 1993 / 635 Регистрация: 26.02.2014 Сообщений: 1,457 |
||||
13.11.2015, 03:34 |
9 |
|||
Часть сообщений перенёс в новый тред «Сымитировать нажатие клавиши ENTER».
К примеру есть специальные знаки @#$%^&* у каждого свои предназначение Такого специального символа в синтаксисе языка командной строки и пакетных файлов нет. Но есть команда, которая осуществляет переход на новую строку. Эта команда — команда Windows Batch file echo.
. Для записи в коде выводимого текста в одну строку можно создать и своё сочетание символов для перехода на новую строку в виде расширения какой-нибудь переменной, например Windows Batch file set "n=&echo." . Пример:
. Результат: (c) Корпорация Майкрософт .
2 |
Покинул форум 4660 / 1304 / 335 Регистрация: 07.05.2015 Сообщений: 2,600 |
|
13.11.2015, 12:57 |
10 |
esc 13 или 14 — не помню точно В ASCII cr — это 13, а lf — 10 (14 — это soh).
Такого специального символа в синтаксисе языка командной строки и пакетных файлов нет. Вы запамятовали сказать, что есть побочные эффекты некоторых других команд, например, единственный символ < или > в командном файле сделает примерно то же, что и Enter.
Люди есть ли такой знак только испольняющей кнопки [Enter] ??? Если есть PowerShell, можно «нажать» Enter, послав через SendKeys соответсвующий сигнал.
0 |
It can be solved with a single echo.
You need a newline character n
for this.
There are multiple ways to get a new line into the echo
1) This sample use the multiline caret to add a newline into the command,
the empty line is required
echo Hello^
world
2) The next solution creates first a variable which contains one single line feed character.
set n=^
rem ** Two empty lines are required
Or create the new line with a slightly modified version
(set n=^
%=DONT REMOVE THIS=%
)
And use this character with delayed expansion
setlocal EnableDelayedExpansion
echo Hello!n!world
To use a line feed character with the percent expansion you need to create a more complex sequence
echo Hello^%n%%n%world
Or you can use the New line hack
REM Creating a Newline variable (the two blank lines are required!)
set n=^
set NL=^^^%n%%n%^%n%%n%
REM Example Usage:
echo There should be a newline%NL%inserted here.
But only the delayed expansion of the newline works reliable, also inside of quotes.
It can be solved with a single echo.
You need a newline character n
for this.
There are multiple ways to get a new line into the echo
1) This sample use the multiline caret to add a newline into the command,
the empty line is required
echo Hello^
world
2) The next solution creates first a variable which contains one single line feed character.
set n=^
rem ** Two empty lines are required
Or create the new line with a slightly modified version
(set n=^
%=DONT REMOVE THIS=%
)
And use this character with delayed expansion
setlocal EnableDelayedExpansion
echo Hello!n!world
To use a line feed character with the percent expansion you need to create a more complex sequence
echo Hello^%n%%n%world
Or you can use the New line hack
REM Creating a Newline variable (the two blank lines are required!)
set n=^
set NL=^^^%n%%n%^%n%%n%
REM Example Usage:
echo There should be a newline%NL%inserted here.
But only the delayed expansion of the newline works reliable, also inside of quotes.
Есть следующий bat файл с кодом
for /l %%i in (1,1,10) do echo <? phpкод ?> >%%i.php
Нужно сделать чтобы он создавал файлы вот так
for /l %%i in (1,1,10) do echo
<?
phpкод
?> >%%i.php
Но так попробовал не работает.
-
Вопрос заданболее трёх лет назад
-
7626 просмотров
echo off
for /l %%i in (1,1,10) do (
echo ^<^?php > %%i.php
echo php code .. >> %%i.php
echo ^?^>php >> %%i.php
)
Знак ^ = экранирует спец символы
Если надо пустую строку, то можно сделать так echo. >> %%i.php
(т.е. точка на конце echo)
В первой команде используется > чтобы перезаписать файл при повторном вызове, в отличие от >> который добавляет данные без перезаписи
Пригласить эксперта
Если код длинный, вы замучаетесь выводить его через echo. Положите его в отдельный файл и перенаправляйте вывод type для этого файла в нужный, либо делайте конкатенацию через copy.
-
Показать ещё
Загружается…
07 февр. 2023, в 23:29
3000 руб./за проект
07 февр. 2023, в 23:29
51000 руб./за проект
07 февр. 2023, в 23:02
2000 руб./за проект