简体   繁体   中英

Open a file and filter it using a regular expression

I have a large logfile and I want to extract (write to a new file) certain rows. The problem is I need a certain row and the row before. So the regex should be applied on more than one row. Notepad++ is not able to do that and I don't want to write a script for that.

I assume I can do that with Powershell and a one-liner, but I don't know where to start ...

The regular expression is not the problem, will be something like that ^#\\d+.*?\\n.*?Failed.*?$

So, how can I open a file using the Powershell, passing the regex and get the rows back that fits my expression?

Look at Select-String and -context parameter:

If you only need to display the matching line and the line before, use (for a test I use my log file and my regex - the date there)

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

If you need to manipulate it further, store the result in a variable and use the properties:

$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

If there are more lines that match the regex, access them with brackets:

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM