I want to use sed to replace something like $some latex$
or
$$
some latex
$$
with {% math %}some latex {% endmath %}
or
{% math %}
some latex
{% endmath %}
I try sed to solve this problem but a command like
sed -e 's/\$\([^\$]\{1,\}\)\$/{% math %}\1{% endmath %}/g' filename
doesn't work for $some latex$
and I don't know how to deal with multi-line. How can I do this?
The only problem you are facing here is capturing newline or whitespace , which is solved by following regex.
Regex: (?:\\$*)(\\s*)some latex(\\s*)(?:\\$*)
Flags used:
g
for global search. Explanation:
(?:\\$*)(\\s*)
captures the whitespace or newline after leading $
or $$
(\\s*)(?:\\$*)
captures the whitespace or newline before trailing $
or $$
Replacement to do: {% math %}\\1some latex\\2{% endmath %}
Try this with sed :
sed -e ' /\$\$/{s/\$\$/{% math %}/;:a;N;/\$\$/!ba;s/\$\$/{% endmath %}/};s/^\(\$\)\(.*\)\(\$\)$/{% math %}\2{% endmath %}/' sourcefile
Multiline is preserved.
Update :
It seems there is a BSD (OS X?) sed issue with semi colons .
It should work replacing it with new lines :
sed -e '
/\$\$/ {
s/\$\$/{% math %}/
:a
N
/\$\$/!ba
s/\$\$/{% endmath %}/;}
s/^\(\$\)\(.*\)\(\$\)$/{% math %}\2{% endmath %}/
' sourcefile
I also updated the last s
command to match lines like $ \\$ $
mentioned in you comments.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.