i have a log file from postgresql that has log entries of the format;

LOG:  execute <unnamed>: /match this here/
DETAIL:  parameters: /also want to filter this line/

I thought it might be possible with

grep -v --after-context=1 'match this here' /my/log/file.log

but it doesn't work. is there some sed/awk/grep magic, or do i have to do some perl?

link|improve this question

54% accept rate
feedback

4 Answers

As far as I know you cannot do this with grep alone.
awk can do it pretty simple:

awk -v skip=-1 '/match this here/ { skip = 1 } skip-- >= 0 {next } 1' /my/log/file.log

edit:
I assumed that you cannot match the second line by any regex and you really want to match line containing X and the line afterwards. If you can match against a string, it's a lot easier:

egrep -v "match this here|also want to filter this line" /my/log/file.log

link|improve this answer
feedback

Are you intending to use "-v" to prevent 'match this here' from displaying the first line? "-v" inverts your expression to say "display lines that don't match 'match this here'". I'm not on an *nix box right now but I think you could do something like this if you only wanted the second line to show:

grep --after-context=1 'match this here' /my/log/file.log | grep -v '^LOG:' | grep -v '^-'

This should print both lines but the second grep statement should hide the first line that starts with LOG:

Try that and good luck.

link|improve this answer
feedback

Another way to use awk:

awk '/match this here/ {getline; next} {print}' file.log
link|improve this answer
feedback

It's not entirely clear what you want to achieve. If you want to /match this here/ and then print the next line then

sed -n '/match this here/{n;p}' /my/log/file.log

DETAIL:  parameters: also want to filter this line

If you want to /match this here/ and then print the matched line and the one following it then

sed -n '/: match this here/{p;n;p}' /my/log/file.log

LOG:  execute <unnamed>: match this here
DETAIL:  parameters: also want to filter this line

With grep you can

grep -A 1 'match this here' /my/log/file.log 

LOG:  execute <unnamed>: match this here
DETAIL:  parameters: also want to filter this line

if you have multiple matches each is separated by --

grep -A 1 'match this here' /my/log/file.log
LOG:  execute <unnamed>: match this here
DETAIL:  parameters: also want to filter this line
--
LOG:  execute <unnamed>: match this here
DETAIL:  parameters: also want to filter this line

And you can

grep -A 1 'match this here' /my/log/file.log | grep -v 'match this here'

to remove the first line if that's what you want.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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