这两个命令都不会创建多行文本:
Set-Content .\test.md 'Hello`r`nWorld'
Set-Content .\test.md 'Hello\r\nWorld'
只有这个才能
Set-Content .\test.md @("Hello`nWorld")
你知道这是为什么吗?
发布于 2022-10-26 08:29:19
- By contrast, `'...'` strings are [_verbatim_ strings](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Quoting_Rules#single-quoted-strings) that do _not_ interpret their contents - even ``` instances are used as verbatim (literally).
`
(所谓的回勾符)在PowerShell中充当转义字符,而不是 \
.。- That is, in _both_ `"..."` and `'...'` strings a `\` is a literal.
- (However, `\` _is_ the escape character in the context of [regexes (regular expressions)](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Regular_Expressions), but it is then the _.NET regex engine_ that interprets them, not PowerShell; e.g.,
"`r" -match '\r'
是$true
:(内插的)文本CR字符。匹配它的转义正则表达式)。
至于,你尝试过
"Hello`nWorld"
是一个使其工作的"..."
字符串。- By contrast, enclosing the string in `@(...)`, the [array-subexpression operator](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Operators#array-subexpression-operator--), is _incidental_ to the solution. ([`Set-Content`](https://learn.microsoft.com/powershell/module/microsoft.powershell.management/set-content)'s (positionally implied) `-Value` parameter is _array_-valued anyway (`System.Object[]`), so even a _single_ string getting passed is coerced to an array).
Set-Content
向输出文件添加了一个尾随的平台本机换行符;使用-NoNewLine
来抑制它,但请注意,这样做也不会在多个输入对象的(字符串表示)之间放置换行符,如果适用的话(在您的情况下只有一个)。因此(注意-NoNewLine
和尾随`n
):
Set-Content -NoNewLine .\test.md "Hello`nWorld`n"
可选阅读:PowerShell行为的设计原理:
为什么PowerShell不像其他语言一样使用反斜杠作为转义字符?
由于\
必须(也)在上(最初为Windows-)起作用,使用作为转义字符--从(POSIX兼容的)外壳中可知,Bash - is not 是一个选项E 271
,因为\
E 175用作E 177路径分隔符E 278E 179Windows上的E 280。
如果\是转义字符,则必须使用Get-ChildItem C:\\Windows\\System32而不是Get-ChildItem C:\Windows\System32,这在shell中显然是不切实际的,因为在shell中处理文件系统路径是非常常见的。
因此,`**,必须选择a
不同的字符,这实际上是所谓的_回勾**:至少在美国的键盘上,打字很容易(就像\一样),而且它的好处是很少(作为自身)出现在现实世界的字符串中,因此很少需要输入。
请注意,Windows上的旧版本shell cmd.exe也必须选择一个不同的字符:它选择了^,即所谓的插入符。
为什么它不像其他语言一样使用单引号和双引号?
不同的语言做出了不同的设计选择,但在使"..."字符串内插,但'...'字符串没有,遵循现有的语言在
,即与
POSIX兼容的shell,如Bash
。作为对后者的改进,PowerShell还支持将逐字'嵌入到'...'中,转义为'' (例如,'6'' tall')。
考虑到PowerShell对向后兼容性的承诺,这种行为不会改变,特别是考虑到它对语言是多么的基础。
从概念上讲,您可以认为引用字符串所使用的方面应该与它是否是内插分开,这样您就可以为了语法的方便而自由地选择一种或另一种引用风格,同时单独控制是否应该进行内插。
因此,假设PowerShell可以使用单独的sigil来进行字符串内插,比如$"..."和$'...' (类似于C#现在提供的内容,尽管它显然只有一个字符串引用样式)。(顺便说一句: Bash和Ksh确实有这种语法形式,但它具有不同的用途(字符串的本地化),很少用于实践)。
然而,在实践中,一旦您了解了"..."和'...'如何在PowerShell中工作,就不难使它们按预期工作。
有关基本特性,请参见
这个答案
中PowerShell、 和POSIX兼容的shell*并置。
https://stackoverflow.com/questions/74211150
复制相似问题