【问题标题】:Powershell regex replace line that contains ONLY certain charactersPowershell 正则表达式替换仅包含某些字符的行
【发布时间】:2019-02-28 17:58:01
【问题描述】:

由于我执行了其他操作,我使用 get-content -raw 读取了一个文件。

$c = get-content myfile.txt -raw

我想将仅包含字符“*”或“=”的每一行全部替换为“hare”

我试试

$c -replace "^[*=]*$","hare"

但这并没有成功。它适用于简单的字符串输入,但不适用于包含 CRLF 的字符串。 (其他不涉及字符类的正则表达式替换操作工作正常。)

测试: 给定一个两行的输入文件

*=** 
keep this line ***
***=

输出应该是

hare
keep this line ***
hare

尝试了很多东西,没有运气。

【问题讨论】:

    标签: regex powershell


    【解决方案1】:

    您应该使用(?m) (RegexOptions.Multiline) 选项使^ 匹配行首,$ 匹配行尾位置。

    但是,有一个警告:带有多行选项的 .NET 正则表达式中的 $ 锚点仅在换行符、LF、"`n"、char 之前匹配。您需要确保在$ 之前有一个可选的(或者如果它始终存在,则为强制性)CR 符号。

    你可以使用

    $file -replace "(?m)^[*=]*\r?$", "hare"
    

    Powershell 测试演示:

    PS> $file = "*=**`r`nkeep this line ***`r`n***=`r`n***==Keep this line as is"
    PS> $file -replace "(?m)^[*=]*\r?$", "hare"
    hare
    keep this line ***
    hare
    ***==Keep this line as is
    

    【讨论】:

    • 谢谢!我曾尝试过多行,但关于 CR 的提示是我所缺少的。
    【解决方案2】:

    试试这个:

    $c = get-content "myfile.txt" -raw
    $c -split [environment]::NewLine | % { if( $_ -match "^[*= ]+$" ) { "hare" } else { $_ } }
    

    【讨论】:

      猜你喜欢
      • 2011-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多