简体   繁体   中英

Search & Replace in Text files - With a RegEx Variable Pattern

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.

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

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM