0
votes

I am trying to replace a string in each file lets call the string XXX I would like to replace it with the regex pattern variable text found between Start and END

Currently it simply replaces the word, and then just does not replace.

$Pat1 = [regex]  '(START)*(END)'      # Find Variable between these 2 first

Get-ChildItem * -Recurse | Where-Object {
    $_.Attributes -ne "Directory"
} | ForEach-Object {
    (Get-Content $_) -replace "XXX","$Pat1" | Set-Content -path $_
}

Example Text Below

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque porttitor augue quis urna suscipit lobortis. Cras eu magna sem. Quisque dictum feugiat convallis.

START File Name 1 END Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque porttitor augue quis urna suscipit lobortis. Cras eu magna sem. Quisque dictum feugiat convallis.

XXX Vestibulum risus quam, volutpat iaculis ipsum in, vehicula dictum urna. Suspendisse dui tortor, faucibus et tellus vitae, malesuada consequat velit.

=================================

1
You never executed a match for $Pat1, so you're replacing with a null value.TheMadTechnician
Hi TMT - do I add it like this "$Pat1" -matchwp44
I have been trying this also: Foreach-Object {$_ -replace "XXX", "(?i)(?<=START ).*?(?= *END)"} | - nothing seems to work :(wp44
Con you give exemple of what you've got in your files and what you want to obtain.JPBlanc

1 Answers

0
votes

The question is very unclear, but I'm guessing that you want to replace XXX with the value between START and END in the file and the not regex-pattern itself. If so, try this:

$Pat1 = [regex]  'START(.*?)END'      #Find Variable between these 2 first

Get-ChildItem * -Recurse  | Where-Object { -not $_.PSIsContainer } |
ForEach-Object {
    $text = (Get-Content $_ -Raw)
    $value = [regex]::Match($text, $Pat1).Groups[1].Value
    $text -replace "XXX",$value | Set-Content -path $_
}

Be aware the -replace works like 'text' -replace 'regex-pattern', 'stringvalue' The right value does not accept a regex-pattern, but only a string (which may include $0,$1 etc. to add the full match, captured group 1 etc.)