in reply to file alteration

That was fun: Here is a oneliner that does what you want:

perl -ne 'chomp; if (s/^A$// .. ($m=s/^B$//)){if($m){ print "A\n$p\B\n" if $p;$p=""}else{$p.=$_."\n" if $_} } ' datafile

see trick nr4 on https://blogs.oracle.com/ksplice/entry/the_top_10_tricks_of