Similar to tripleee's answer, I would also use awk for this purpose.
The main idea is to implement a simple state machine.
Simple example
As a simple example, first try to find three consecutive lines of banana.
Consider the pattern-action statement
/banana/ { bananas++ }
For every line matching the regex banana
, it increases the variable bananas
(in awk, all variables are initialised with 0).
Of course, you want bananas
to be reset to 0 when there is non-matching line, so your search starts from the beginning:
/banana/ { bananas++; next }
{ bananas = 0 }
You can also test for values of variables in the pattern of actions.
For example, if you want to print "Found" after three lines containing banana
, extend the rule:
/banana/ {
bananas++
if (bananas >= 3) {
print "Found"
bananas = 0
}
next
}
This resets the variable bananas
to 0, and prints the string "Found".
How to proceed further
Using this basic idea, you should be able to write your own awk script that handles all the cases.
First, you should familiarise yourself with awk (pattern, actions, program execution).
Then, extend and adapt my example to fit your needs.
- In particular, you probably need an associative array
matched
, with indices "banana", "orange", "lime".
- You set
matched["banana"] = $0
when the current line matches /banana/
. This saves the current line for later output.
- You clear that whole array when the current line does not match any of your expressions.
- When all strings are found (
matched[s]
is not empty for every string s
), you can print the contents of matched[s]
.
I leave the actual implementation to you.
As others have said, your description leaves many corner-cases unclear.
You should figure them out for yourself and adapt your implementation accordingly.