In my application, I have modified all IP addresses, in order not to disturb the actual production system. As a result, my application is throwing lots of exceptions. Those are kept in a logfile, called filename
.
I would like to filter the exceptions, but I don’t want to see the ones, caused by the modification of the IP addresses.
This sounds very easy, because those exceptions are preceded by a line, containing Failed to connect
.
Let’s see how to do this:
Filter on exceptions:
grep "Exception" filename
Show also the previous line:
grep -B 1 "Exception" filename
Do not show the lines, containing "Failed to connect":
grep -B 1 "Exception filename | grep -v "Failed to connect"
=> No, this is not what I want: this filters out the lines, containing the words "Failed to connect", but the actual exceptions are still shown. How can I not only filter out the exceptions too?
My filename
contents are something like:
... Failed to connect ...
... Exception ...
...
... (lots of these)
...
... <something else than "Failed to connect">
... Exception ...
...
... Failed to connect ...
... Exception ...
...
... (again lots of these)
...
I’m only interested in the lines ... Exception ...
who are not preceded by "Failed to connect".
When I press man grep
, it ends with:
GNU grep 3.4 ... 2019-12-29
Does anybody have an idea?
Thanks in advance
>Solution :
Using gnu-grep
you may be able to do this:
grep -zoP '(?m)^(?!.*Failed to connect).+\R.*Exception.*\R' file
... foo bar baz
... Exception ...
# where file content is
cat file
.. Failed to connect ...
... Exception ...
...
... (lots of these)
...
... foo bar baz
... Exception ...
...
... Failed to connect ...
... Exception ...
...
... (again lots of these)
...
Command Details:
-z
: Operate on full file instead of one line at a time-o
: Return only matched text-P
: Enable PCRE mode(?m)
: Enable MULTILINE mode^
: Match a line start(?!.*Failed to connect)
: Negative lookahead to assert failure when we haveFailed to connect
anywhere on a line.+\R
: Match 1+ of any characters followed by a line break.*Exception.*\R
: Match 0+ of any characters then textException
then again 0 or more of any characters followed by a line break