问题
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?
回答1:
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.
回答2:
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:
gfor 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 %}
Regex101 Demo
来源:https://stackoverflow.com/questions/35815988/replace-latex-with-and-multi-line