0

I need to remove the same html code from many files. I tried to write an powershell script but its not working.

$htmlFiles = Get-ChildItem . *.html -rec
$old = '<form method="GET" action="http://localhost/index.php" name="head2">`r`n
                <input type="hidden" name="akcja" value="szukaj">`r`n
                <input type="hidden" name="ind" value="0" >`r`n
    `r`n
                <table border="0" cellpadding="1" cellspacing="0" style="margin-left:11px" >`r`n
                  `r`n
                            SOME MORE CODE
                 `r`n
                </table>`r`n
            `r`n
    </form>'

$new = ""

foreach ($file in $htmlFiles)
{
    (Get-Content $file.PSPath) |
    Foreach-Object { $_ -replace $old, $new} |
    Set-Content $file.PSPath
 }

I used so much `r`n because i have this same in html files. Maybe I need to do this with regex but regex for over 50 lines is too much for me. I think script is not working because whitespaces doesnt match. How to make it work?

My script runs but with no effect on a files ps. it needs to work on windows

1

2 Answers 2

1

Agree with using the here-string, but you're doing a multi-line replace. this means you need to retrieve your HTML as a single, multi-line string and use a multi-line regex.

Does this work for your application?

$htmlFiles = Get-ChildItem . *.html -rec    

 $regex = 
 @'
(?ms)\s*<form method="GET" action="http://localhost/index.php" name="head2">\s*
.+?
\s*</form>\s*
'@
$new = ''

foreach ($file in $htmlFiles)
{
    (Get-Content $file.PSPath -raw) -replace $regex,$new  |
    Set-Content $file.PSPath
 }
Sign up to request clarification or add additional context in comments.

2 Comments

there's no effect with this script ;/
i'm writing a whole code fragment with \s* for white spaces and this didnt replace it. but when I use .* its working, why?
0

Try using a here-string instead of inserting escaped special characters which will probably mess up your regex matching.

@'
<form method="GET" action="http://localhost/index.php" name="head2">
    <input type="hidden" name="akcja" value="szukaj">
...
</form>
'@

Of course it will only work if the exact same formatting is used in each file.

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.