2016-09-25 75 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 .... –