Grepping multiple terms with different arguments

Grep -e 'term1' -A1 -e 'term2' -A3

The above code always searches for either term and prints results + next three lines.

I'm trying to print out:

foo foo foo term1 bar bar bar
line right after the above
--
la la la la term2 so so so
line right after the above
and again
and again

I've tried grep because I'm most familiar with it. Any solution is fine. Bash environment. Perl if necessary but a grep/awk/sed/other cli command preferred (want to learn the above)

Many thanks!
dkozel

nawk '/term1|term2/ {c=4}c&&c--' myFile

vgersh99: Thanks for the quick reply.

*sigh* I have access to awk and gawk on this computer. Unfortunately I'm working on a system I can't install software on so nawk isn't an option. I'll try that out when I get to my own system.

I tried just ^nawk^gawk but that didn't work.
*** glibc detected *** gawk: free(): invalid pointer: 0x000000000066bfe0 ***

I don't know if that's an issue with our gawk or a syntax error (you would think that would be handled better...)

If there are more ideas wonderful, if not, I'll try nawk on when I get a chance.

Thanks again.

that's sounds like a gawk installation issue.
try 'awk' instead.

awk ran. head smack Should have tried that.

The result isn't as required however. The awk statement is equivalent to

dkozel $ grep "term1\|term2" -A3 testfile

the problem is that I would like to print a different number of lines following each search term.

dkozel $ awk '/term1|term2/ {c=4}c&&c--' testfile
term1
1
2
3
term2
1
2
3

testfile

term1
1
2
3
4
5
6
term2
1
2
3
4
5
6

Desired output

term1
1
term2
1
2
3

Your 'desired' output is equivalent to to your grep.

awk '/term1|term2/ {c=(/term1/)?2:4}c&&c--'

Thank you. That works.

My apologies for likely being unclear. My initial grep statement and your first awk statement had the same output, lines containing search terms and the following three lines. It was the different number of following lines for each term that I was unable to figure out.

For other's references this can be extended to n search terms.

awk '/term1|term2|term3/ {c=(/term1/)?2:(/term2/)?3:4}c&&c--' testfile

The above will print term1 and the following 1 lines ( two lines total ), term2 and the following 2 lines (three lines total ), and term 3 and the following 3 lines ( four lines total).

The only potential 'gotcha' might be when one of the 'term-s' falls within the 'scope' of the previously encountered 'range'. I'm not sure what the 'desirable' output should be in this case....

term2
1
term1
1
2
3
4
5
6