2009-12-09 35 views
17

Desidero aggiungere contenuto nel mezzo di un file di testo in PowerShell. Sto cercando uno schema specifico, quindi aggiungo il contenuto dopo di esso. Nota questo è nel mezzo del file.Inserisci contenuto nel file di testo in PowerShell

Quello che ho attualmente è:

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

Tuttavia, questo non funziona. Sto assumendo perché $ _ è immutabile, o perché l'operatore + = non lo modifica correttamente?

Qual è il modo di aggiungere il testo a $ _ che si rifletterà nella seguente chiamata Set-Content?

+1

L'unico problema con il tuo originale è che non hai prodotto nulla. Basta aggiungere un $ _ dopo il blocco if() {} ... – Jaykul

risposta

29

Invia solo il testo extra, ad es.

(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 

Potrebbe non essere necessario l'extra `` n` dal PowerShell schiererà terminare ogni stringa per voi.

10

ne dite di questo:

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

Penso che sia abbastanza straight-forward. L'unica cosa non ovvia è il "$ &", che si riferisce a ciò che è stato abbinato a "modello". Ulteriori informazioni: http://www.regular-expressions.info/powershell.html

+0

Buon suggerimento. Non funziona per quello che devo fare, ma funzionerebbe in un caso più generale. – Jeff

+0

@Jeff, credo che sia funzionalmente equivalente al tuo. –

1

Questo problema può essere risolto utilizzando gli array. Un file di testo è una matrice di stringhe. Ogni elemento è una linea di testo.

$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 
Problemi correlati