2009-12-09 67 views
17

我想將內容添加到Powershell中的文本文件中。我正在尋找一個特定的模式,然後在它後面添加內容。注意這是在文件的中間。將內容插入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 2009-12-09 21:22:07

回答

29

只輸出額外文本例如

(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 

因爲PowerShell會爲您終止每個字符串,所以您可能不需要額外的``n`。

10

如何:

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

我認爲這是相當直接的。唯一不明顯的是「$ &」,它是指「模式」匹配的內容。更多信息:http://www.regular-expressions.info/powershell.html

+0

好的建議。不適合我需要做的事情,但會在更一般的情況下工作。 – Jeff 2009-12-14 17:25:30

+0

@Jeff,我相信它在功能上等同於你的。 – 2009-12-21 13:29:27

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 
相關問題