Test file is given below:PATTERN1abcPATTERN2defPATTERN2ghI want to print line between PATTERN1 and 2nd match of PATTERN2:PATTERN1abcPATTERN2defPATTERN2
How to print lines between pattern1 and 2nd match of pattern2?
text processing;awk;sed
Here's one way to do it with sed:sed '/PATTERN1/,$!d;/PATTERN2/{x;//{x;q;};g;}' infileThis just deletes all lines (if any) up to the first occurrence of PATTERN1 and then, on each line that matches PATTERN2 it exchanges buffers. If the new pattern space also matches, it means it's the 2nd occurrence so it exchanges back and quits (after auto-printing). If it doesn't match it means it's the 1st occurrence so it copies the hold space content over the pattern space via g (so now there's a line matching PATTERN2 in the hold buffer) and goes on...and another way with awk:awk '/PATTERN1/{t=1}; t==1{print; if (/PATTERN2/){c++}}; c==2{exit}' infileIt starts printing and counting lines matching PATTERN2 only when encountering a line matching PATTERN1 and exits when counter reaches 2.