Regex 在输出中查找并替换为正则表达式
我得到了一个巨大的LaTeX文件,其中对数字的引用很糟糕,比如说Regex 在输出中查找并替换为正则表达式,regex,sed,latex,Regex,Sed,Latex,我得到了一个巨大的LaTeX文件,其中对数字的引用很糟糕,比如说 "... So in the figure 3-12 we see ... similar to figure 3-1..." 它应该在哪里 "... So in the figure \ref{fig:3-12} we see ... similar to figure \ref{fig:3-1}..." 为了节省时间,愚蠢的我,我选择了一个查找/替换,如: 查找:图3- 替换:图\ref{图3- 它返回: "... So
"... So in the figure 3-12 we see ... similar to figure 3-1..."
它应该在哪里
"... So in the figure \ref{fig:3-12} we see ... similar to figure \ref{fig:3-1}..."
为了节省时间,愚蠢的我,我选择了一个查找/替换,如:
查找:图3-
替换:
图\ref{图3-
它返回:
"... So in the figure \ref{fig:3-12 we see ... similar to figure \ref{fig:3-1..."
现在结束括号
sed 's#/ref{fig:3-\d+#\ref{fig:3-\d+}#g' main.tex
产生
"... So in the figure \ref{fig:3-\d+} we see ... similar to figure \ref{fig:3-\d+}..."
朋友们,怎么了?谢谢。你可以用这个
sed
:
s="... So in the figure 3-12 we see ... similar to figure 3-1..."
sed -E 's/[0-9]+-[0-9]+/\\ref{fig:&}/g' <<< "$s"
... So in the figure \ref{fig:3-12} we see ... similar to figure \ref{fig:3-1}...
s=“…因此,在图3-12中,我们看到…类似于图3-1…”
sed-E的/[0-9]+-[0-9]+/\\ref{fig:&}/g'您可以捕获单词figure
后的任何数字和连字符:
s="... So in the figure 3-12 we see ... similar to figure 3-1..."
echo $s | sed -E 's#(figure +)([0-9-]+)#\1\\ref{fig:\2}#g'
看
关于如何使用*.bak副本(在Ubuntu中测试)进行就地替换的示例:
详细信息
(figure+
-第1组:捕获figure
子字符串和1个或多个空格(替换为[:blank:][]+
以匹配任何空格或制表符)
([0-9-]+)
-第2组:一个或多个数字或-
替换为:
\1
-对组1值的替换反向引用
\\ref{fig:
-文字\ref{fig:
子字符串(反斜杠必须转义,因为它是“特殊”字符)
\2
-对组2值的替换反向引用
}
-a}
字符
您正在匹配文本中的每一个\d+-\d+
。使图成为您模式的一部分。
sed -i.bak -E 's#(figure +)([0-9-]+)#\1\\ref{fig:\2}#g' main.tex