简体   繁体   English

用$和多行替换LaTeX

[英]Replace LaTeX with $ and multi-line

I want to use sed to replace something like $some latex$ or 我想用sed代替$some latex$

$$
some latex
$$

with {% math %}some latex {% endmath %} or {% math %}some latex {% endmath %}

{% math %}
some latex
{% endmath %}

I try sed to solve this problem but a command like 我尝试用sed解决此问题,但是命令如下

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. 不适用于$some latex$并且我不知道如何处理多行。 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*)(?:\\$*) 正则表达式: (?:\\$*)(\\s*)some latex(\\s*)(?:\\$*)

Flags used: 使用的标志:

  • g for global search. g进行全局搜索。

Explanation: 说明:

  • (?:\\$*)(\\s*) captures the whitespace or newline after leading $ or $$ (?:\\$*)(\\s*)$$$$空格

  • (\\s*)(?:\\$*) captures the whitespace or newline before trailing $ or $$ (\\s*)(?:\\$*)在结尾$$$前捕获空格或换行符

Replacement to do: {% math %}\\1some latex\\2{% endmath %} 替换操作: {% math %}\\1some latex\\2{% endmath %}

Regex101 Demo Regex101演示

Try this with sed : 尝试使用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 . 似乎存在带有半冒号的BSD(OS X?) sed问题

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. 我还更新了last s命令以匹配您注释中提到的$ \\$ $类的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM