2012-08-07 88 views
0

所以我需要在多個txt文件中刪除幾塊txt。該文件是這樣的:使用PowerShell刪除文本塊

Header 
Value 
Data 
    <DefaultValue> 
     sdf 
     asdfsdf 
     asfkfkf 
    </DefaultValue> 
Data3 
Data2 
    <DefaultValue> 
     sdfdffff 
      asdfsasdfddf 
     asfkf 
    </DefaultValue>** 
Dat 
End 

我需要刪除與默認值開始的行塊,並與/默認值

最終結果應該是這樣的:

Header 
Value 
Data 
Data3 
Data2 
Dat 
End 

不幸的是,它不是一個正確形成的XML文件,所以XML節點刪除將無法正常工作。

有什麼建議嗎?

回答

2

我用這個來解決需要添加第三方加入字符串函數:

$filePath = '.\Desktop\new 3.txt' 
$text = "" 
Get-Content $filePath | % {$text += $_ + "NEWLINE"} 
$text = $text -Replace "<Default.+?DefaultValue>","" 
$text.Replace("NEWLINE","`r`n") 

的收益率:

Header 
Value 
Data 

Data3 
Data2 
    ** 
Dat 
End 

爲了使這個重複的,你想幹什麼這樣的事情:

Get-ChildItem -Path C:\logs\ -Filter "*.txt" | % { 
    $text = "" 
    Get-Content $_.FullName | % {$text += $_ + "NEWLINE"} 
    $text = $text -Replace "<Default*DefaultValue>","" 
    $text.Replace("NEWLINE","`r`n") | Out-File $_.FullName -Force 
} 

祝你好運,把你的數據備份起來,並檢查從另一個更優雅的答案用戶。

+0

你太棒了!非常感謝! – user1582582 2012-08-07 17:53:30

+0

隨時接受答案,如果它的工作。 – 2012-08-07 18:01:59