MrGrant
MrGrant

Reputation: 161

Find multiple lines spanning text and replace using PowerShell

I am using a regular expression search to match up and replace some text. The text can span multiple lines (may or may not have line breaks). Currently I have this:

 $regex = "\<\?php eval.*?\>"

Get-ChildItem -exclude *.bak | Where-Object {$_.Attributes -ne "Directory"} |ForEach-Object {
 $text = [string]::Join("`n", (Get-Content $_))
 $text -replace $RegEx ,"REPLACED"}

Upvotes: 4

Views: 10095

Answers (3)

majkinetor
majkinetor

Reputation: 9056

One should use the (.|\n)+ expression to cross line boundaries since . doesn't match new lines.

Upvotes: 0

stej
stej

Reputation: 29479

Try this:

$regex = New-Object Text.RegularExpressions.Regex "\<\?php eval.*?\>", ('singleline', 'multiline')

Get-ChildItem -exclude *.bak |
  Where-Object {!$_.PsIsContainer} |
  ForEach-Object {
     $text = (Get-Content $_.FullName) -join "`n"
     $regex.Replace($text, "REPLACED")
  }

A regular expression is explicitly created via New-Object so that options can be passed in.

Upvotes: 5

Keith Hill
Keith Hill

Reputation: 202072

Try changing your regex pattern to:

 "(?s)\<\?php eval.*?\>"

to get singleline (dot matches any char including line terminators). Since you aren't using the ^ or $ metacharacters I don't think you need to specify multiline (^ & $ match embedded line terminators).

Update: It seems that -replace makes sure the regex is case-insensitive so the i option isn't needed.

Upvotes: 1

Related Questions