我在PowerShell阅读线上遇到问题。我的要求是:
使用select字符串,如果找到模式,则读取行直到“。”找到并在一行中显示输出。
我的文件看起来像这样:
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”,则读取整行直到下一个“。”找到了。因为该行被截断了。
所需的输出是:
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行。并且输出也没有显示在一行中。
答案 0 :(得分: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.