1

I have a similar question to this: Unix grep regex containing 'x' but not containing 'y'

The twist is that, I d like to grep the files around my search with -C5.

So the grep this myfile | grep -v that won't work.

example: let say myfile is as follows:

**
**
alpha
**
**
##
##
alpha beta
##
##

I d like to grep :

**
**
alpha
**
**

how would I achieve this?

Orkun Ozen
  • 6,665
  • 7
  • 53
  • 86

1 Answers1

2

You can use this gnu grep with a PCRE regex:

grep -C2 -P '^(?!.*beta).*alpha' file 

**
**
alpha
**
**

Regex '^(?!.*beta).*alpha' uses a negative lookahead to match a line that contains alpha anywhere but doesn't contain beta.

If gnu grep is not available:

awk '/alpha/ && !/beta/{print line[NR-2]; print line[NR-1]; n=NR}
     n && NR<=n+2; {line[NR]=$0}' file

**
**
alpha
**
**
anubhava
  • 713,503
  • 59
  • 514
  • 593
  • 2
    Your regex solution and its explanation is not correct. It must be `grep -C2 -P '^(?!.*beta).*alpha' file`, because `(?!.*beta)alpha` matches any line with `alpha` word that is not followed with `beta` anwhere *after* `alpha`, and `beta alpha` would get returned. – Wiktor Stribiżew Jun 22 '18 at 08:17
  • Yes good point Wiktor. It should have been `'^(?!.*beta).*alpha'` to match `alpha` anywhere. – anubhava Jun 22 '18 at 08:20