Ste*_*e H 6 sed text-processing regular-expression
试图更新一些乳胶代码。四行:
something $^\text{TT}$ and more stuff
something $^\text{T}$ and more stuff
something $^\text{M\times N}$ and more stuff
something $^\text{T} {otherstuff}$
Run Code Online (Sandbox Code Playgroud)
应该变成
something $^{\text{TT}}$ and more stuff
something $^{\text{T}}$ and more stuff
something $^{\text{M\times N}}$ and more stuff
something $^{\text{T}} {otherstuff}$
Run Code Online (Sandbox Code Playgroud)
换句话说,用额外的{...}.
我使用的尝试sed如下
sed 's/\^\\text{\(.*\)}/\^{\\{text{\1}}/' testregex
Run Code Online (Sandbox Code Playgroud)
这适用于前三行,但最后一行不起作用并产生
something $^{\text{T} {otherstuff}}$
Run Code Online (Sandbox Code Playgroud)
反而。问题是,sed是最后一个匹配}的每一行,但我需要它匹配第一个}后\text{
此外,如果这可以在同一条线上多次工作,那就太好了,例如,
^\text{1} la la la ^\text{2}
Run Code Online (Sandbox Code Playgroud)
应该变成
^{\text{1}} la la la ^{\text{2}}
Run Code Online (Sandbox Code Playgroud)
我敢肯定只有一个小小的修改就可以使它工作,但我无法弄清楚,这让我发疯。提前致谢!
您快到了!不要\text{}像使用 那样在块内查找“0 个或多个字符” ,而是\\text{\(.*\)}查找“0 个或多个非}字符”:
$ sed 's/\^\\text{\([^}]*\)}/\^{\\{text{\1}}/g' foo.tex
something $^{\{text{TT}}$ and more stuff
something $^{\{text{T}}$ and more stuff
something $^{\{text{M\times N}}$ and more stuff
something $^{\{text{T}} {otherstuff}$
Run Code Online (Sandbox Code Playgroud)
g添加到末尾的I 打开全局匹配,这意味着该行上的所有匹配项都将被替换。请注意,这假设匹配是非重叠的,它不适用于这样的事情:
something $^{\{text{$^{\{text{BB}}$}}$ and more stuff
Run Code Online (Sandbox Code Playgroud)
不过,我假设这不是问题。
克服贪婪正则表达式问题的一种方法是显式查找一串非定界符,然后是定界符。同时,您可以通过以下方式简化替换语法:
sed 's/\^\(\\text{[^}]*}\)/\^{\1}/' input.tex
Run Code Online (Sandbox Code Playgroud)
应该可以使用
sed 's/\^\(\\text{[^}]*}\)/\^{\1}/g' input.tex
Run Code Online (Sandbox Code Playgroud)
每行有多个匹配项。