在PowerShell中将内容插入到文本文件中

37

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

目前我的代码如下:

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

然而,这并不起作用。我假设是因为 $_ 是不可变的,或者因为 += 操作符不能正确地修改它?

如何在 $_ 中追加文本以便在以下 Set-Content 调用中反映出来?


1
你原来的代码唯一的问题是没有输出任何内容。只需要在 if(){} 块后面添加一个 $_ 即可... - Jaykul
7个回答

56

只需输出额外的文本,例如:

(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会自动为您在每个字符串上进行换行。


16

好的建议。对于我需要做的事情不起作用,但在更一般的情况下可以使用。 - Jeff
@Jeff,我相信它在功能上与你的代码等效。 - dan-gph

3

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

$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... #>

$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

0

以下脚本适用于在指定路径下的多个文件中,在某个模式后面插入文本。

$fileNames = Get-ChildItem "C:\Example" -Recurse |
select -expand fullname

foreach ($FileName in $filenames) 
{
$pattern = "pattern"

[System.Collections.ArrayList]$file = Get-Content $FileName

$insertafter = @()

for ($i=0; $i -lt $file.count; $i++) {
  if ($file[$i] -match $pattern) {
    $insertafter += $i+1 #Record the position of the line after this one
  }
}

#Now loop the recorded array positions and insert the new text
$insertafter | Sort-Object -Descending | ForEach-Object { 
$file.insert($_, "text inserted after pattern") }


Set-Content $FileName $file
}

0

txt、properties、pf 等文件中精确匹配文本的解决方案。

$FileName = "C:\Progress\OpenEdge\properties\fathom.properties"
$Pattern = "[Fathom]"  
$FileOriginal = Get-Content $FileName

[String[]] $FileModified = @() 
Foreach ($Line in $FileOriginal)
{   
    $FileModified += $Line
    if ( $Line.Trim() -eq $Pattern ) 
    {
        #Add Lines after the selected pattern 
        $FileModified += "Autostart=true"
        
    } 
}
Set-Content $fileName $FileModified

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

这个有什么优势,超过了已被接受的答案? - General Grievance

0

我曾试图使用XAML文本框来完成这个任务。这个线程给了我开始工作所需的起点。

对于其他想要完成此任务的人:

#Find and replace matched line in textbox
$TextBox.Text = ($TextBox.Text) | 
Foreach-Object {
    if ($_ -match "pattern")
    {
        #Replace matched line 
        $_ -replace "pattern", "Text To Add"
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接