A buffer of lines needs to be used.
Give a try to this:
awk -v N=4 -v pattern="example.*pattern" '{i=(1+(i%N));if (buffer[i]&& $0 ~ pattern) print buffer[i]; buffer[i]=$0;}' file Set N value to the Nth line before the pattern to print.
Set patternvalue to the regex to search.
buffer is an array of N elements. It is used to store the lines. Each time the pattern is found, the Nth line before the pattern is printed.