S.Spieker
S.Spieker

Reputation: 7365

How to replace a string between two other strings

I am trying to replace in several files the following type of string:

StringResourceHelper.[STRING_OF_INTEREST]ResourceString() with Strings.[STRING_OF_INTEREST]

For example I would like to replace:

StringResourceHelper.HelpResourceString() with Strings.Help

So far, I got a simple replacement which would work if the second string would not be important:

    Get-ChildItem . *.cs -Recurse |
      Foreach-Object {
       $c = ($_ | Get-Content) 
       $c = $c -replace 'StringResourceHelper.','Strings.'
       $c | Set-Content $_.FullName -Encoding UTF8
    }

But this does not help me, because I also have Strings like StringResourceHelper.Culture which should not be touched.

Any help is appreciated.

Upvotes: 1

Views: 2357

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

You need to escape literal dots in your regular expression, otherwise . will match any character except newlines. Something like this should work:

$c = $c -replace 'StringResourceHelper\.(\w*?)ResourceString\(\)', 'Strings.$1'

Also, your code could be simplified a little, like this:

$srch = 'StringResourceHelper\.(\w*?)ResourceString\(\)'
$repl = 'Strings.$1'

Get-ChildItem . *.cs -Recurse | % {
   $filename = $_.FullName
   (Get-Content $filename) -replace $srch, $repl |
       Set-Content $filename -Encoding UTF8
}

Upvotes: 1

Related Questions