【问题标题】:PowerShell: replace newline and connect two linesPowerShell:替换换行符并连接两行
【发布时间】:2021-09-09 18:36:33
【问题描述】:

我正在尝试删除“三”的第一个匹配项上的新行,但我不确定为什么下面的示例不起作用:

$var = 'one two three
four five six
seven'

$var = $var.replace("three`n", 'three ')
$var

期望的输出:

one two three four five six
seven

【问题讨论】:

  • 致潜在的亲密选民:问题可重现的,即在使用 CRLF 换行符的脚本文件中。
  • 如果您的问题尚未得到完全解答,请考虑 accepting 提供答案或提供反馈。

标签: regex windows powershell replace newline


【解决方案1】:

要考虑换行(换行)格式中的变化,请使用-replace operatorregex \r?\n以平台/文件格式中立的方式匹配换行符:

$var = 'one two three
four five six
seven'

$var -replace 'three\r?\n', 'three '

正则表达式 \r?\n 匹配 Windows 格式的 CRLF (\r\n) 和 Unix 格式的 LF(仅限\n)换行符。

上述使用逐字 regex 转义序列,-replace 运算符底层的 .NET 正则表达式引擎会解释这些转义序列。在expandable strings ("...") 中表示为PowerShell 转义序列,换行格式为`r`n`n
您也可以将最后一条语句表示为 $var -replace "three`r?`n", 'three ',但通常最好将 verbatim 字符串 ('...') 传递给 .NET 正则表达式引擎,以避免混淆 PowerShell 解释的内容,向上前面,与 .NET 正则表达式引擎解释的内容。

注意,脚本文件的换行格式决定了其中多行字符串文字的换行格式,所以如果你的脚本文件使用CRLF换行符, "three`n"匹配,因为输入字符串中的 LF ("`n") 前面有一个 CR ("`r")。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 2022-01-25
    • 1970-01-01
    • 2020-04-17
    • 2016-10-27
    相关资源
    最近更新 更多