Could you please try following, written and tested based on your shown samples only in GNU awk
.
awk '
/PATTERN1/ && found1 && !found2{
found1=found2=val=""
}
/PATTERN1/{
found1=1
next
}
/PATTERN2/{
found2=1
if(found1){
print val
}
found1=found2=val=""
next
}
{
val=(val?val ORS:"")$0
}
' Input_file
Output for given samples will be:
ggg
hhh
iii
Explanation: Adding detailed explanation for above.
awk ' ##Starting awk program from here.
/PATTERN1/ && found1 && !found2{ ##Checking if PATTERN1 in current line and found1 is SET and found2 is NOT SET then do following.
found1=found2=val="" ##Nullifying found1, found2 and val variables here.
}
/PATTERN1/{ ##Checking condition if PATTERN1 is found then do following.
found1=1 ##Setting found1 here for flagging.
next ##next will skip all further statements from here.
}
/PATTERN2/{ ##Checking condition if PATTERN2 is found then do following.
found2=1 ##Setting found2 here for flagging.
if(found1){ ##Checking condition if found1 is SET then do following.
print val ##Printing val here.
}
found1=found2=val="" ##Nullifying found1, found2 and val here.
next ##next will skip all further statements from here.
}
{
val=(val?val ORS:"")$0 ##Creating val which has current line value and keep appending it with new line.
}
' Input_file ##Mentioning Input_file name here.