Replace multiline text in a file with Powershell without using Regex

I have the following Powershell script:

$oldCode =  @"
            <div id="time_estimate">
                <!-- some large table -->
            </div>
"@

$newCode = @"
            <div id="time_estimate">
                                <!-- nested divs and spans -->
                                <div id="contact-form">

                                        <?php include "contact-form.php"; ?>
                                </div>
                        </div>
"@

ls *.html | foreach { 
        $fileContent = [System.Io.File]::ReadAllText($_.FullName)
        $newFileContent = $fileContent.Replace($oldCode, $newCode)
        [System.Io.File]::WriteAllText($_.FullName, $newFileContent)
        Write-Host  "`r`n"
        Write-Host  "Processed - $($_.Name)...`r`n" }

This is not like replacing text. Is this a problem with multi-line strings or the limits of the Replace () method? I would rather make a replacement without involving regular expression.

+2
source share
3 answers

What version of PowerShell are you using? If you are using v3 or higher, try the following:

ls *.html | foreach { 
    $fileContent = Get-Content $_.FullName -Raw
    $newFileContent = $fileContent -replace $oldCode, $newCode
    Set-Content -Path $_.FullName -Value $newFileContent
    Write-Host  "`r`n"
    Write-Host  "Processed - $($_.Name)...`r`n" 
}
+2
source

For Pete, don't even think about using regex for HTML.

, , , . Replace() , . -join, ,

$fileContent = [System.Io.File]::ReadAllText($_.FullName)
$theOneString = $fileContent -join ' '
$theOneString.Replace($foo, $bar)

... . , HTML Tidy.

. <div>, . . , </div> . , , .

+1

I would not use string replacements to modify HTML code. For many things that can develop in unexpected directions. Try something like this:

$newCode = @"
<!-- nested divs and spans -->
<div id="contact-form">
  <?php include "contact-form.php"; ?>
</div>
"@

Get-ChildItem '*.html' | % {
  $html = New-Object -COM HTMLFile
  $html.write([IO.File]::ReadAllText($_.FullName))
  $html.getElementById('time_estimate').innerHTML = $newCode
  [IO.File]::WriteAllText($_.FullName, $html.documentElement.outerHTML)
}

If necessary, you can prefix HTML with Tidy :

$newCode = @"
<!-- nested divs and spans -->
<div id="contact-form">
  <?php include "contact-form.php"; ?>
</div>
"@

[Reflection.Assembly]::LoadFile('C:\path\to\Tidy.dll') | Out-Null
$tidy = New-Object Tidy.DocumentClass

Get-ChildItem '*.html' | % {
  $html = New-Object -COM HTMLFile
  $html.write([IO.File]::ReadAllText($_.FullName))
  $html.getElementById('time_estimate').innerHTML = $newCode
  $tidy.ParseString($html.documentElement.outerHTML)
  $tidy.SaveFile($_.FullName) | Out-Null
}
0
source

All Articles