2015-12-01 57 views
0

我需要從許多文件中刪除相同的html代碼。我試圖寫一個PowerShell腳本,但它不工作。腳本刪除多行html代碼

$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 
} 

我用了很多'r`n,因爲我在html文件中有這個相同。也許我需要用正則表達式來完成,但超過50行的正則表達式對我來說太過分了。 我認爲腳本不工作,因爲空格不匹配。如何使它工作?

我的腳本運行但對文件 ps沒有任何影響。它需要在窗口上工作

+0

使用Html Agility Pack進行此類工作:http://www.leeholmes.com/blog/2010/03/05/html-agility-pack-rocks-your-screen-scraping-world/ –

回答

0

嘗試使用here-string而不是插入轉義特殊字符,這可能會混淆正則表達式匹配。

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

當然,只有在每個文件中使用完全相同的格式時才能工作。

1

同意使用這裏的字符串,但你正在做一個多行替換。這意味着你需要檢索你的HTML作爲一個單一的多行字符串,並使用多行的正則表達式。

這是否適合您的應用?

$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 
} 
+0

這個腳本沒有任何效果;/ – Kamil

+0

我正在用\ s *編寫一個完整的代碼片段用於空格,並且這沒有替代它。但是當我使用。*它的工作時,爲什麼? – Kamil