1

I've got some third party log files I'm trying to pull errors out of on the command line.

The logs look like this:

time=1
time=2
time=3
  at com.test.com....
  at com.test.com....
  at com.test2.com....
time=4
time=5
time=6
time=7
time=8
time=9
  at org.badstuff.com...
  at org.badstuff.com...
  at org.badstuff.com...
time=10
time=11

The lines that start with at start with a TAB character, so they can be easily matched.

How can I pull these stack traces out of this file, and a couple of lines before the first stack trace each time? I'm on a Mac, but would prefer a generic solution that works on Mac/Linux if possible, as I have to work on both quite often.

So from my above example, I'd pull out the following

time=2
time=3
  at com.test.com....
  at com.test.com....
  at com.test2.com....
time=8
time=9
  at org.badstuff.com...
  at org.badstuff.com...
  at org.badstuff.com...
3

Just use -After context, -Before context or -Context option in grep, e.g. to fit to your example:

grep -B2 '^\t' file
2

Use grep -B2 -P '^\t' logfile to pick up two lines before each set of matches. You may need to mask out the group separator "--" that is inserted between matches.

Results

$ grep -B2 -P '^\t' /tmp/t
time=2
time=3
        at com.test.com....
        at com.test.com....
        at com.test2.com....
--
time=8
time=9
        at org.badstuff.com...
        at org.badstuff.com...
        at org.badstuff.com...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.