Reading again your description I understand that you want the first match of pattern B from the bottom up until (going up) the first match of pattern A. But the resulting sections should be in the order that the file has.
That requires a lot of logic. The following shell script does it all. Will place the results in the correct internal order in files E and some number, first file (E1) will have the first match from the top, last file will have the last match section.
#!/bin/bash rm -rf resE* E* tac ../example_file.txt | awk 'BEGIN{i=1} /^AK5\*R.*/{p=1} {if(p==1){f="resE" i;print($0)>>f;close(f)}} /^AK2.*/{if(p==1){i++};p=0} ' set -- resE* c=$# for (( i=1;i<=$c;i++)); do pos=$(($c-$i+1)) [ -f "$1" ] && tac "$1" > "E$pos" shift done The resulting ranges will be:
$ cat E1 AK2*777*7777777 AK3*S6*5**3 AK3*A2*5**3 AK4*3*6969*4 AK4*7*6969*4 AK5*R*5 $ cat E2 AK2*777*7777777 AK3*J7*5**3 AK4*3*6969*4 AK5*R*5