1

Below I have a ps1 for finding and appending text defined by regex pattern; i.e. from [pattern] to [pattern]Foo. Is there a simpler way to do this for multiple regex patterns, other than defining each regex as pattern2, pattern3, etc. and creating a separate "ForEach" to correspond to every regex? Because that's how I did it, and it works but it looks very rudimentary.

$pattern1 = [regex]'([___)'
$pattern2 = [regex]'([___)'

Get-ChildItem 'C:\\File\\Location\\*.txt' -Recurse | ForEach {
     (Get-Content $_ | 
     ForEach  { $_ -replace $pattern1, ('$1'+'FOO')} | 
     ForEach  { $_ -replace $pattern2, ('$1'+'FOO')}) |
     Set-Content $_
}
3
  • 1
    You may use alternations: [regex]'(pattern1|pattern2)' Commented Mar 13, 2017 at 22:11
  • BTW [ needs an escape \[ otherwise it's an invalid pattern. Also, use -raw parameter in Get-Content if you're on PowerShell 3 or newer to make processing much faster. Commented Mar 13, 2017 at 22:17
  • You can chain -replace such as Get-Content $_ -replace $pattern1, '$1FOO' -replace $pattern2, '$1FOO' Commented Mar 13, 2017 at 23:06

1 Answer 1

1

If you are replacing with the same replacement pattern, just use alternation:

$pattern = [regex]'(pattern1|pattern2)'

NOTE: in unanchored alternations, you should watch out for the order of the alternatives: if a shorter branch can match at the same location in string, a longer one - if it is present after the shorter one - won't get tested. E.g. (on|one|ones) will only match on in ones. See more about that in the Remember That The Regex Engine Is Eager.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.