#!/usr/bin/sed -f
:loop
# Remove leading non-math stuff
s/^[^$]*//
# If we didn't hit a math start yet, get next line
/^\$\$/! d
# We now have a string starting with $$
# Until we have a starting and an ending point, get more lines
:get
/\$\$.*\$\$/ bgot
N
bget
:got
# We now have a string containing at least one string we want
# Preserve in hold space
h
# Remove everything not inside the pattern and print it
s/^\(\$\$[^$]*\$\$\).*/\1/p
# get text back from hold space
g
# Remove just-printed string
s/^\$\$[^$]*\$\$//
bloop