使用 select 字符串读取行直到 .找到字符
read line using select string until . character found
我在 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 行中。而且输出也没有显示在一行中。
我会使用 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.
我在 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 行中。而且输出也没有显示在一行中。
我会使用 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.