Replace LaTeX with $ and multi-line

假如想象 提交于 2019-12-12 05:15:15

问题


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:

  • 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 %}

Regex101 Demo



来源:https://stackoverflow.com/questions/35815988/replace-latex-with-and-multi-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!