2011-10-05 34 views
0

我試圖在幾百頁中找到一個函數,並使用Powershell刪除它。我可以在一條線上比賽,但我遇到了一些問題,需要進行多線比賽。任何幫助,將不勝感激。Powershell正則表達式查找和刪除函數

功能我試圖找到:我使用的是不匹配的多線

Protected Function MyFunction(ByVal ID As Integer) As Boolean 
    Return list.IsMyFunction() 
End Function 

代碼:

gci -recurse | ?{$_.Name -match "(?i)MyPage.*\.aspx"} | %{ 
    $c = gc $_.FullName; 
    if ($c -match "(?m)Protected Function MyFunction\(ByVal ID As Integer\) As Boolean.*End Function") { 
    $_.Fullname | write-host; 
    } 
} 

回答

3

您可以使用正則表達式中的(?s)標誌。 S代表單線,在一些地方也稱爲dotall,這使得.跨越換行符。

此外,gc逐行讀取,任何比較/匹配將在各行和正則表達式之間進行。儘管在正則表達式上使用正確的標誌,你將不會得到一場比賽。我通常使用[System.IO.File]::ReadAllText()將整個文件的內容作爲單個字符串來獲取。

因此,一個可行的解決方案將是這樣的:

gci -recurse | ?{$_.Name -match "(?i)MyPage.*\.aspx"} | %{ 
    $c = [System.IO.File]::ReadAllText($_.Fullname) 
    if ($c -match "(?s)Protected Function MyFunction\(ByVal ID As Integer\) As Boolean.*End Function") { 
    $_.Fullname | write-host; 
    } 

} 

對於更換,當然你可以使用$matches[0]並使用Replace()方法

$newc = $c.Replace($matches[0],"") 
1

默認情況下,-match運算符將不會搜索。*通過回車。您將需要直接使用.NET Regex.Match功能來指定「單線」搜索選項(在這種情況下,不幸的是命名):

[Regex]::Match($c, 
       "(?m)Protected Function MyFunction\(ByVal ID As Integer\) As Boolean.*End Function", 
       'Singleline') 

請參閱MSDN的Match功能和valid regex options的更多細節。

+0

該解決方案針對搜索的偉大工程。我之所以沒有選擇它作爲答案,是因爲我在回寫內容時遇到了問題。要使用.net [regex] :: replace函數將刪除換行符,而標記爲答案的解決方案將修復搜索問題並保留設置內容的格式。有關更多詳細信息,請參閱http://stackoverflow.com/questions/2726599/powershell-replace-lose-line-breaks再次感謝。 –