How to replace multiple lines of file via powershell

Viewed 193

I have a httpd.conf file, which contains some part like -

<ThisBlock *:4443>
    This Part can contain any random lines
    This Part can contain any random lines
    This Part can contain any random lines
</ThisBlock>

What i want is to swap the above block with this new block using powershell or cmd

<ThisBlock *:4443>
    This Part contain Static lines
    This Part contain Static lines
</ThisBlock>

1 Answers

you could use regex with option SingleLine: all text between the tags are replaced

$newtext = "<ThisBlock *:4443>
    This Part contain Static lines
    This Part contain Static lines
</ThisBlock>"


$text = Get-Content -Path C:\httpd.conf  -Encoding UTF8 -raw
$option = [System.Text.RegularExpressions.RegexOptions]::Singleline 
#i have to escape the char \ becasue is special char
$pattern = "<ThisBlock \*:4443>.*?</ThisBlock>"
$rgx = [regex]::new($pattern, $option)

$result = $rgx.Replace($text, $newtext)
$result
Related