打开文件并使用正则表达式对其进行过滤

ste*_*ema 7 regex powershell file-io

我有一个大的日志文件,我想提取(写入新文件)某些行.问题是我之前需要一行和一行.所以正则表达式应该应用于多行.Notepad ++无法做到这一点,我不想为此编写脚本.

我认为我可以用Powershell和单线程做到这一点,但我不知道从哪里开始......

正则表达式不是问题,会是这样的 ^#\d+.*?\n.*?Failed.*?$

那么,如何使用Powershell打开文件,传递正则表达式并获取适合我表达式的行?

ste*_*tej 8

看看Select-String-context参数:

如果您只需要显示匹配的行和之前的行,请使用(对于测试,我使用我的日志文件和我的正则表达式 - 那里的日期)

Get-Content c:\Windows\System32\LogFiles\HTTPERR\httperr2.log  |
    Select-String '2011-05-13 06:16:10' -context 1,0
Run Code Online (Sandbox Code Playgroud)

如果需要进一步操作它,请将结果存储在变量中并使用以下属性:

$line = Get-Content c:\Windows\System32\LogFiles\HTTPERR\httperr2.log  |
        Select-String '2011-05-13 06:16:10' -context 1

# for all the members try this:
$line | Get-Member

#line that matches the regex:
$line.Line
$line.Context.PreContext
Run Code Online (Sandbox Code Playgroud)

如果有更多行与正则表达式匹配,请使用括号访问它们:

$line = Get-Content c:\Windows\System32\LogFiles\HTTPERR\httperr2.log  |
        Select-String '2011-05-13 06:16:10' -context 1
$line[0] # first match
$line[1] # second match
Run Code Online (Sandbox Code Playgroud)

  • 如果您只想要之前的行而不是之后的行,则可以使用-Co​​ntext 1,0. (5认同)