经过一个不眠之夜,阅读了这里的所有答案,阅读了很多SS64 > CMD,经过很多尝试和错误,我发现:
(几乎)终极解决方案
TL;DR
...对于早期采用者。
| Important! |
| Use a text editor for C&P that supports Unicode, e.g. Notepad++! |
设置换行环境变量...
...在当前 CMD 会话中
| 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:
...当前用户
| 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:
...本地机器
| 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
为什么差不多?
它不适用于在同一打印行中未配对(打开和关闭)的双引号,除非唯一未配对的双引号是文本的最后一个字符,例如:
-
作品:""echo %\n%...after "newline". Before "newline"...%\n%...after "newline"(在每个打印的行中配对)
-
作品:echo %\n%...after newline. Before newline...%\n%...after newline"(唯一不成对的双引号是最后一个字符)
-
不起作用:echo "%\n%...after newline. Before newline...%\n%...after newline"(双引号未配对在同一打印行)
完全双引号文本的解决方法(灵感来自Windows batch: echo without new line):
set BEGIN_QUOTE=echo ^| set /p !="""
...
%BEGIN_QUOTE%
echo %\n%...after newline. Before newline...%\n%...after newline"
它适用于完全单引号的文本,例如:
echo '%\n%...after newline. Before newline...%\n%...after newline'
附加值:转义字符
| 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://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#text-formatting
set ESC=
有关颜色,另请参阅 https://imgur.com/a/EuNXEar 和 https://gist.github.com/gerib/f2562474e7ca0d3cda600366ee4b8a45。
第二个附加值:轻松获取 Unicode 字符
通过关键字获取 87,461 个 Unicode 字符 (AToW) 的绝佳页面:https://www.amp-what.com/。
原因
-
Ken's answer 中的版本显然有效(我没有尝试过),但不知何故……嗯……你看:
set NLM=^
set NL=^^^%NLM%%NLM%^%NLM%%NLM%
-
派生自user2605194 和user287293 答案的版本(在'=' 和'^' 之间没有任何内容):
set nl=^&echo:
set \n=^&echo:
部分工作但失败,行首的变量为echoed:
> echo %\n%Hello%\n%World!
echo & echo:Hello & echo:World!
echo is ON.
Hello
World
由于第一个 echo 的参数为空白。
-
所有其他人都或多或少地调用了三个echos。
-
我喜欢短的单行字。
背后的故事
为了防止此处的答案中建议的set \n=^&echo: 回显空白(以及打印其状态),我首先记得 Alt+25 5 用户,当时 Novell 是一个广泛使用的网络,并且使用了像 437 和 850 这样的代码页。但是现在 Unicode 中的 0d255/0xFF 是 ›Ÿ‹ (Latin Small Letter Y with diaeresis)。
然后我记得Unicode 中有more spaces,而不是普通的 0d32/0x20,但它们都被认为是空格,并导致与 ›␣‹ 相同的行为。
但还有更多:零宽度空格和连接符,它们不被视为空格。它们的问题是,你不能对它们进行 C&P,因为它们的宽度为零,没有什么可供选择的。所以,我复制了一个接近其中之一的 头发空间 (U+200A),它就在 零宽度空间 (U+200B) 之前到 Notepad++ ,打开其 Hex-Editor 插件,找到其位表示 E2 80 8A 并将其更改为 E2 80 8B。成功!我的\n 环境变量中有一个不可见的非空白字符。