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

时间:2009-12-09 17:49:10

标签: powershell

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

目前我所拥有的是:

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

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

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

5 个答案:

答案 0 :(得分:35)

只输出额外的文字,例如

(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

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

答案 1 :(得分:12)

这个怎么样:

(gc $fileName) -replace "pattern", "$&`nText To Add" | sc $fileName

我认为这是相当直截了当的。唯一不显而易见的是“$&”,它指的是“模式”匹配的内容。更多信息:http://www.regular-expressions.info/powershell.html

答案 2 :(得分:1)

这个问题可以通过使用数组来解决。文本文件是字符串数组。每个元素都是一行文字。

$FileName = "C:\temp\test.txt"
$Patern = "<patern>" # the 2 lines will be added just after this pattern 
$FileOriginal = Get-Content $FileName

<# create empty Array and use it as a modified file... #>

[String[]] $FileModified = @() 

Foreach ($Line in $FileOriginal)
{    
    $FileModified += $Line

    if ($Line -match $patern) 
    {
        #Add Lines after the selected pattern 
        $FileModified += "add text'
        $FileModified += 'add second line text'
    } 
}
Set-Content $fileName $FileModified

答案 3 :(得分:0)

我正在尝试执行此操作,但是使用XAML文本框。该线程为我提供了使其工作所需的起点。

对于其他想要这样做的人:

__exit__()

答案 4 :(得分:0)

(Get-Content $fileName) | Foreach-Object {
        if ($_ -match "pattern") 
        {
            write-output $_" Text To Add"
        }
        else{
            write-output $_
            }
    } | Set-Content $fileName