Search for patterns on different lines

im using the following code to search a log for entries on two different lines:

awk 'BEGIN{count=0} /'"${firstpattern}"'/,/'"${secondpattern}"'/ { print; if ($0 ~ /'"${thirdpattern}"'/){count++}; } END { print count }' data.txt
firstpattern="start error log"
secondpattern="i am logging the errors now"
thirdpattern="App crashed"

data.txt

blahblahblahblahahahahahahahahahahahlalalalalalalalalal
auffkffiaooojf jafkaf kafkakf akkkkkkkkkkkfaf kafkafk akfkafka
March 22 2017 start error log
today is lovely.  it is not raining. No snow.  fantastic
......
I am logging the errors now
tomorrow. it will rain. stay in doors.
App crashed
.......
I am fine today. Just dont bother me.  
Im watching a movie tomorrow.  You;re not invited.

Now, when the above awk code is run on the data.txt file, it will pull out only the text im interested in, which is:

March 22 2017 start error log
today is lovely.  it is not raining. No snow.  fantastic
......
I am logging the errors now
tomorrow. it will rain. stay in doors.
App crashed

sometimes, there will be many instances where multiple "start error log" are present. but neither "I am logging the errors now" nor "App crashed" strings will be present. there will be other errors in their place, errors i dont care about. in these instances, the errors that I do care about "I am logging the errors now" and "App crashed" are usually towards the bottom under one of the other "start error log" strings.

so what ends up happening is that, the awk code tries to print everything it finds from the first "start error log" instance, to the last.

i want the awk code to skip printing an entire chunk of lines if the three patterns im looking for are not all there.

It seems in your script have pattern 2 and 3 reversed, no?
If so, try something like this:

awk -v p1="start error log" -v p2="I am logging the errors now" -v p3="App crashed" '
  s!="" {
    s=s RS $0
    if($0~p3) {
      if (s~p2)
        print s
      s=""
    }
  } 
  $0~p1 {
    s=$0
  }
' data.txt

---
Also in you sample secondpattern variable, the "I" was written as "i"

1 Like