title: Searching for a specific string above another specific string
body: <p>I am trying to write a (fairly) simple log parser to help me with debugging an application fault.</p>
  
  <p>What I am currently trying to achieve is finding each instance of "Connection timed out", then finding the string "Processing file" which comes somewhere between 10-30 lines above "Connection timed out" (not always the same number of lines between).</p>
  
  <p>My code currently looks something like this:</p>
  
  <pre><code>!#/bin/bash
  connectionTimeOutLines=`zcat filename | grep -n "Connection timed out" | cut -f1 -d:` #get the line number of all instances of connection timed out
  for timeOutLine in "$connectionTimeOutLines"
  do
       # get the date and time the event was logged
       logDate=`zcat filename | sed "${timeOutLine}q;d" | awk '{print $1}' | awk '{print substr($0,2)}'`
       logTime=`zcat filename | sed "${timeOutLine}q;d" | awk '{print $2}'`
       # need to get the "file processed line" here
       fileProcessed="unsure what I am doing here"
       echo "$fileProcessed timed out at $logTime on $logDate" &gt;&gt; /tmp/logFile.log
  done
  </code></pre>
  
  <p>I have edited out part of the code for brevity as it doesn't have any bearing on the question... which is: how do I find an instance of a string that comes before another string?</p>
  
  <p>I can't search based purely on "Processing file" as that string appears each time a file is processed, whereas I am looking for instances where that processing has failed (with "Connection timed out").</p>
  
  <p>TBH, I'm not 100% I have explained myself correctly, so I apologise in advance - please ask for any clarification where necessary!</p>