Tuesday, May 12, 2015

Multi-line text replacement with Powershell

A number of times recently I have had need of a script to replace a chunk of code or XML in a few dozen files. I've been enjoying Powershell lately; so I decided to use it to write the script. A couple challenges presented. First, the text replacement had to handle line breaks. Second, it had to handle (escape) special characters. It took me a couple hours and tips from a few different blog posts & Stack Overflow questions to get it right. So, I'll post the product here.

$oldCode = @"
/// <summary>
        /// My Old XML Comment
        /// </summary>
        public static new string ThingID

$newCode = @"
/// <summary>
        /// My New XML Comment
        /// </summary>
        public new const string ThingID = 

Get-ChildItem .\ -Recurse –Include “*.YourFileExtension” | foreach-object {
    $text = Get-Content $_.Fullname -Raw
    $text = $text -replace $oldCode, $newCode
    $text | Out-File $_.Fullname -Force utf8

Obviously I've simplified my script a bit, but the above script should be completely functional. Notice that you can essentially just paste in your find & replace text. No special work to do in escaping characters. These two posts were especially helpful in getting this result:
  • http://personal-code.blogspot.com/2013/03/powershell-string-literals-and-formating.html
  • http://stackoverflow.com/a/20642482/698978

No comments:

Post a Comment