我有一个包含这些行的LaTeX
文件:foo.tex
\includegraphics[width=0.49\textwidth]{img1}
\includegraphics{img2}
\subfloat{\includegraphics[width=0.3\textwidth]{img3}}
\subfloat{\includegraphics{img4}}
我想替换文件中的这些行以添加文件扩展名,如下所示:
\includegraphics[width=0.49\textwidth]{img1.png}
\includegraphics{img2.png}
\subfloat{\includegraphics[width=0.3\textwidth]{img3.png}}
\subfloat{\includegraphics{img4.png}}
我开始尝试使用sed
这个命令:
cat foo.tex | sed 's/\(includegraphics.*[a-z,0-9,\-]}\)/\1.png}/g' > bar.tex
但它返回:
\includegraphics[width=0.49\textwidth]{img1}.png
\includegraphics{img2}.png
\subfloat{\includegraphics[width=0.3\textwidth]{img3}.png}
\subfloat{\includegraphics{img4}.png}
如何修复sed
添加文件扩展名的命令?
编辑
图像文件名不仅是img1、img2等。
答案1
$ sed '/\\includegraphics/s/img[0-9]*/&.png/g' input
\includegraphics[width=0.49\textwidth]{img1.png}
\includegraphics{img2.png}
\subfloat{\includegraphics[width=0.3\textwidth]{img3.png}}
\subfloat{\includegraphics{img4.png}}
替换操作的正则表达式查找img
后跟任意数量的数字(包括零数字),并附加到.png
匹配的末尾。
稍微更强大的版本,仅执行替换里面大括号:
$ sed '/\\includegraphics/s/{\(img[0-9]*\)}/{\1.png}/g' input
\includegraphics[width=0.49\textwidth]{img1.png}
\includegraphics{img2.png}
\subfloat{\includegraphics[width=0.3\textwidth]{img3.png}}
\subfloat{\includegraphics{img4.png}}
{img3}
这会在包含 的任何行上查找(例如)\includegraphics
,从中提取img3
,追加.png
,并将其重新包装在新的大括号中,以获得所需的{img3.png}
.