profiler
profiler

Reputation: 627

Filtering file in Unix

I have a big problem with filtering output error file. The log file:

Important some words flags
Line 1
Line 2
...
Line N
Important some words
Line 1
Line 2
...
Line N
Important some words
Line 1
Line 2
...
Line N
Important some words flags
Line 1
Line 2
...
Line N

So, some section has word "flags" another not.

Desired output file is:

Important some words flags
Line 1
Line 2
...
Line N
Important some words flags
Line 1
Line 2
...
Line N

Only section with line, which one was started via "Important" and ended "flags".

All sections have a random number of lines.

So I can't use something like that:

grep -B1 -P '!^Important*flags' logfile

Because I don't know how many lines will be after/before that line...

Upvotes: 0

Views: 58

Answers (2)

JJoao
JJoao

Reputation: 5347

perl -n0E 'say /(Important\N*flags.*?)(?=Important|$)/sg'

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 753525

There are more succinct ways to handle it, but this is fairly clear:

awk '/^Important.*flags$/ { p = 1; print; next }
     /^Important/         { p = 0;        next }
                          { if (p) print }'
  • If the line is important and flagged, set p to 1, print the line, and skip to the next.
  • Else, if the line is important (but not flagged), set p to 0 and skip to the next.
  • Otherwise, it is an 'unimportant' line; print it if p is non-zero (which means that the last important line was flagged).

Any lines before the first Important line will find p is 0 anyway, so they won't be printed.

Upvotes: 4

Related Questions