tags:

views:

449

answers:

2

I want to add content into the middle of a text file in Powershell. I'm searching for a specific pattern, then adding the content after it. Note this is in the middle of the file.

What I have currently is:

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

However, this doesn't work. I'm assuming because $_ is immutable, or because the += operator doesn't modify it correctly?

What's the way to append text to $_ that will be reflected in the following Set-Content call?

+6  A: 

Just output extra the extra text e.g.

(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

You may not need the extra `n since PowerShell will line terminate each string for you.

Keith Hill
+2  A: 

How about this:

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

I think that is fairly straight-forward. The only non-obvious thing is the "$&", which refers to what was matched by "pattern". More info: http://www.regular-expressions.info/powershell.html

dangph
Good suggestion. Doesn't work for what I need to do but would work in a more general case.
Jeff
@Jeff, I believe it is functionally equivalent to your one.
dangph