2009-12-09 84 views
17

Quiero agregar contenido en el medio de un archivo de texto en Powershell. Estoy buscando un patrón específico, luego agrego el contenido después de él. Tenga en cuenta que esto está en el medio del archivo.Insertar contenido en archivo de texto en Powershell

Lo que tengo actualmente es:

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

Sin embargo, esto no funciona. Estoy asumiendo porque $ _ es inmutable, o porque el operador + = no lo modifica correctamente?

¿Cuál es la manera de agregar texto a $ _ que se reflejará en la siguiente llamada Set-Content?

+1

El único problema con su original es que no produjo nada. Simplemente añada un $ _ después del bloque if() {} ... – Jaykul

Respuesta

29

Simplemente muestre el texto adicional, p.

(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 

Puede que no necesite el `` n` adicional ya que PowerShell terminará en línea cada cadena para usted.

10

¿Qué tal esto:

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

creo que es bastante sencilla. La única cosa que no es obvia es "$ &", que se refiere a lo que fue emparejado por "patrón". Más información: http://www.regular-expressions.info/powershell.html

+0

Buena sugerencia. No funciona para lo que necesito hacer pero funcionaría en un caso más general. – Jeff

+0

@Jeff, creo que es funcionalmente equivalente a la suya. –

1

Este problema se puede resolver mediante el uso de matrices. Un archivo de texto es una matriz de cadenas. Cada elemento es una línea de texto.

$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 
Cuestiones relacionadas