Awk to match a pattern and perform a search after the first pattern

Hello Guyz

I have been following this forum for a while and the solutions provided are super useful. I currently have a scenario where i need to search for a pattern and start searching by keeping the first pattern as a baseline

ABC
DEF
LMN
EFG
HIJ
LMN
OPQ

In the above text i need to search for EFG first and then keeping EFG as the starting point, i need to search for LMN. I should not get the LMN before EFG.

Any help would be greatly appreciated!!

Thanks,
Rick..

awk '/EFG/{p=1}/LMN/&&p{print "LMN at line "NR}' file
1 Like

Thanks Elixir. That works like a charm. can you please explain how it works.

awk '/EFG/{p=1}         # set variable p to 1 when the pattern EFG is found
/LMN/&&p{               # when pattern LMN is found AND p is set (when EFG has been found)
print "LMN at line "NR} # include line number to make sure that the correct record is selected' file
1 Like

Thanks again elixir. Even if the pattern EFG is not found, can i still search for LMN. In that case my output should produce 2 lines

That would be as simple as:

awk '/LMN/' file

Yeah. i agree. But i wanted to search for EFG, if EFG is found the output should print LMN. if EFG is not found, then my output should print LMN twice. Can i combine that in a single awk script

awk '/EFG/{foundEFG=1;t=""}
/LMN/&&foundEFG{print;next}
/LMN/{t=t?t RS $0:$0}
END{if(!foundEFG) print t}' file
1 Like

Amazing!! That works great. When you have a moment, please let me know how it works.

Thanks again
Rick..