Question: I have asked similar question [here](https://stackoverflow.com/questions/47412728/grep-for-error-and-print-all-the-lines-containing-2-strings-above-and-below-erro), but this one I feel is more complicated than that so, asking in different post.

```
foo foo foo foo foo
Import blash blah blah
foo foo foo foo foo 
blah blah blah blah 
Error loading file
blah blah blah blah
blah blah blah blah
query run ends
foo foo foo foo
Import blash blah blah
foo foo foo foo foo 
foo foo foo foo foo 
Exception occurred
blah blah blah blah
blah blah blah blah
query run ends
Import blash blah blah
foo foo foo foo foo 
foo foo foo foo foo 
query run ends

```

In the pattern similar to above, I want to grep all the contents between all **Import** and **ends** if **Error** or **Exception** exist in between them.
And in that process I want to exclude those *Import & ends* combination which doesn't have any *Error or Exception* string.

**Note:**
---------

The lines between **Import & ends** strings are not constant, it may vary.

Expected:
---------

```
Import blash blah blah
foo foo foo foo foo 
blah blah blah blah 
Error loading file
blah blah blah blah
blah blah blah blah
query run ends
Import blash blah blah
foo foo foo foo foo 
foo foo foo foo foo 
Exception occurred
blah blah blah blah
blah blah blah blah
query run ends

```

Answer: 
The same sed as yesterday with one more condition.

```
sed '/^Import/!d;:A;N;/\nImport/{h;s/.*\n//;bA};/ends$/!bA;h;s/\nException//;tB;s/\nError//;tB;d;:B;x' infile

```
GNU **`awk`** solution (assuming `Import` keyword doesn't occur within intermediate text):

```
awk -v RS='Import' '$0~/\<(Error|Exception)/{ printf "%s%s",RS,$0 }' file

```

* `-v RS='Import'` - treat `Import` keyword as record separator

---

The output:

```
Import blash blah blah
foo foo foo foo foo 
blah blah blah blah 
Error loading file
blah blah blah blah
blah blah blah blah
query run ends
Import blash blah blah
foo foo foo foo foo 
foo foo foo foo foo 
Exception occurred
blah blah blah blah
blah blah blah blah
query run ends

```