在Powershell中将内容插入文本文件

Jef*_*eff 27 powershell

我想在Powershell中将内容添加到文本文件的中间.我正在搜索特定模式,然后在其后添加内容.请注意,这是在文件的中间.

我现在拥有的是:

 (Get-Content ( $fileName )) | 
      Foreach-Object { 
           if($_ -match "pattern")
           {
                #Add Lines after the selected pattern
                $_ += "`nText To Add"
           }
      }
  } | Set-Content( $fileName )
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用.我假设因为$ _是不可变的,或者因为+ =运算符没有正确修改它?

将文本附加到$ _的方法是什么,这将反映在以下Set-Content调用中?

Kei*_*ill 42

只输出额外的文字,例如

(Get-Content $fileName) | 
    Foreach-Object {
        $_ # send the current line to output
        if ($_ -match "pattern") 
        {
            #Add Lines after the selected pattern 
            "Text To Add"
        }
    } | Set-Content $fileName
Run Code Online (Sandbox Code Playgroud)

您可能不需要额外的``n`,因为PowerShell会为您终止每个字符串.


dan*_*gph 12

这个怎么样:

(gc $fileName) -replace "pattern", "$&`nText To Add" | sc $fileName
Run Code Online (Sandbox Code Playgroud)

我认为这是相当直截了当的.唯一不明显的是"$&",它指的是与"模式"相匹配的东西.更多信息:http://www.regular-expressions.info/powershell.html