我有一个名为a.tex的.tex文件,其中包含许多行文本,如下例所示:
begin{pycode}
Some text right here, let's say Text 1A: like: There are #cat and #dog.
end{pycode}
Some text right here, let's say Text 1B: like: One day the #dog tried to run away.
begin{pycode}
Some text right here, let's say Text 2A: like: There are #cat and #dog and #pig.
end{pycode}
Some text right here, let's say Text 2B: like: There is #something here.
我想用"所提到的文本的数量"代替任何#,例如句子"There are #cat and #dog."这是一只狗和一只猫。因为它在课文1A中。有一天,狗想要逃跑。一天,那只狗想要逃跑。还有"有#猫、#狗和#猪"。改成"有2只猫、2只狗和2只猪",等等。
输出是一个.tex文件,此更改应用于整个文档。
所以我想要的是:
begin{pycode}
Some text right here, let's say Text 1A: like: There are 1cat and 1dog.
end{pycode}
Some text right here, let's say Text 1B: like: One day the 1dog tried to run away.
begin{pycode}
Some text right here, let's say Text 2A: like: There are 2cat and 2dog and 2pig.
end{pycode}
Some text right here, let's say Text 2B: like: There is 2something here.
我在这方面没有最小的工作。我的想法是从第一行开始搜索和替换。例如,如果我们看到"begin{pycode}"然后s = s+1(对于一些计数变量s)并搜索#,然后将其替换为s,直到我们遇到下一个&;begin{pycode}&;
我正在用这种方法寻找解决方案,但仍需要时间来解决。
谢谢你的帮助。
$ awk '/\begin[{]pycode}/{s++} {gsub(/#/,s); print}' a.tex
begin{pycode}
Some text right here, let's say Text 1A: like: There are 1cat and 1dog.
end{pycode}
Some text right here, let's say Text 1B: like: One day the 1dog tried to run away.
begin{pycode}
Some text right here, let's say Text 2A: like: There are 2cat and 2dog and 2pig.
end{pycode}
Some text right here, let's say Text 2B: like: There is 2something here.
您可以像这样使用'sed'命令:
sed -e 's/searchFor/replaceWith/g' filename
在你的例子中:
sed -e 's/#/'$i'/g' a.tex > output.tex
它的作用是在a.tex文件中找到所有'#'字符串的出现,用$i的值替换它们并将它们保存到output.tex文件中。如果您想读取并保存到同一个文件,只需使用:
sed -i 's/#/'$i'/g' a.tex
你可以在这里阅读更多关于'sed'命令:Linux sed命令