2016-09-25 28 views
1

我在PowerShell閱讀行中遇到問題。我的要求是:直到讀取使用選擇字符串的行。找到字符

使用選擇字符串,如果找到一個模式,比讀行直到「。」。找到並顯示在一行中的輸出。

我的文件看起來像這樣:

file: this is the first 
file for 
read. 
error:this is the error. 
data: this is the data. 
file: this is the 
second file. 

在文件中,如果「文件」被發現,不是閱讀全線直到下一個「」被發現。因爲該行被截斷。

所需的輸出是:

file: this is the first file to read. 
file: this is the second file. 
//file name will be removed before 

我嘗試像:

$totalFile = Select-String *.log -pattern "file:" -CaseSensitive -Context 0,1| % {$_.line}| Out-File "result.txt" 

但上下文不工作,因爲有些文件是2線有些是在第3行。並且輸出不在一行中顯示。

回答

1

我會用regex捕捉所需的輸出,並使用-replace刪除換行符:

Get-ChildItem -Path 'yourPath' -filter '*.log' | ForEach-Object { 
    $content = Get-Content $_.FullName -Raw 
    [regex]::Matches($content, "(file[^\.]+\.?)") | ForEach-Object { 
     $_.Groups[0].Value -replace '\r?\n' 
    } 
} 

輸出:

file: this is the first file for read. 
file: this is the second file. 
+0

感謝您的幫助.. ..但我不確定這是否適用於版本2 ....因爲這顯示錯誤... –

+0

Get-Content:無法找到參數匹配參數名稱'Raw'。這是錯誤的第一行 –

+0

只是省略了-raw參數,它仍然可以工作。另外,你應該提到你正在使用Powershell-v2 .... –

相關問題