首页 > 解决方案 > 在 PowerShell 中跨多行匹配日志条目

问题描述

我正在尝试搜索包含跨越多行的日志条目的日志文件。例子:

BEGIN
...
123456
...
END
BEGIN
...
456789
...
END

我想搜索一个特定的数字 (123456),但打印从前面的 BEGIN 标记到 END 标记的所有内容。如何在 PowerShell 中完成此操作?

我尝试了几个正则表达式,但没有得到它的工作。我到目前为止的代码是:

$id = '123456'

$pattern = 'BEGIN(.|\s)*?'+$id+'(.|\s)*?END'

$matches = Select-String -Path "C:\temp\logile.log" -Pattern $pattern

不知道为什么这不起作用。有没有其他方法可以让它工作?

标签: powershell

解决方案


我会将日志分成多个部分,并进行回顾

foreach ($Section in (Get-Content C:\temp\logile.log -raw) -split '(?<=END\r?\n?)' -ne ''){
    if($section -match '123456'){
        $Section
    }
}

样本输出:

BEGIN
...
123456
...
END

推荐阅读