Anonymous Monk's suggestion is the right one, just a bit elliptic. Let's phrase this another way:
- You're going through the file a line at a time.
- If you see a line you might want (a "Query" line), you save it in a variable and keep reading lines.
- If you see a "hits" line that matches your criterion, the line you saved was one you want. Print it or stick it in an array for later, or...
- If you see a "hits" line and it doesn't match your criterion, then you don't want the "Query" you saw previously. Throw it away by setting the variable to "".
I didn't write out the code because I think it might be more useful to you to write the code yourself. You shouldn't need anything more complicated than one variable to keep the query line in, another one to read the next line from <STDIN> into, a while() loop to keep reading until you're out of lines, and an a couple of if() statements (is this line a "query" line, is this line a "hits" line, does this "hits" line meet my "I want the last 'Query' line" criterion) inside the loop. You don't even need a trailing check outside the loop, because a "hits" line always follows a "Query" line.