Awk eqivalent to grep -C <num>

0

I want to print 5 lines of context around each line that matches "foo" but not "foobar".

I can do the match easily enough via <output> | awk '/foo/ && !/foobar/' but I can't figure out how to show context like <output> | grep -C 5 'foo' would do.

I'd settle for figuring out the above compound conditional in a grep one-liner as well.

javanix

Posted 2015-09-11T17:04:02.480

Reputation: 609

Answers

0

I have this from an answer I gave to a similar question which I cant find anymore:

awk -v context=5 '
BEGIN{ held = -1 }
{ for(i = context;i>0;i--)lb[i] = lb[i-1];
  lb[0] = sprintf("%s:%d:%s",FILENAME,NR,$0);
  held++;
}
/foo/ && !/foobar/{
 if(held>context)held = context;
 for(i = held;i>0;i--)print lb[i]
 held = -1;
 max = NR+context
}
{ if(NR<=max){ print lb[0]; held = -1 }
  else{ if(held==context)print "--" }
}
'

If your grep is gnu and does perl pcre regexps, you do can do:

grep -P '(?!foobar)foo'

which means look forward and don't match foobar, followed by foo.

meuh

Posted 2015-09-11T17:04:02.480

Reputation: 4 273