![使用列表文件中的 keywords\index{keywords} 替换文件中的关键字](https://linux22.com/image/1610783/%E4%BD%BF%E7%94%A8%E5%88%97%E8%A1%A8%E6%96%87%E4%BB%B6%E4%B8%AD%E7%9A%84%20keywords%5Cindex%7Bkeywords%7D%20%E6%9B%BF%E6%8D%A2%E6%96%87%E4%BB%B6%E4%B8%AD%E7%9A%84%E5%85%B3%E9%94%AE%E5%AD%97.png)
我正在尝试在 Linux 下在 LaTeX 文件中生成索引条目。我有两个文件:file1.txt
包含所有索引条目
cats\index{cat}
dogs\index{dog}
elephants\index{elephant}
rats\index{rat}
该animals.tex
文件包含故事文本。
elephants are afraid of rats but are not scared of cats and dogs.
我怎样才能用 file1.txt 中的动物替换 .tex 文件中的不同动物?以获取以下文本:
Elephants\index{elephant} are afraid of rats\index{rat} but are not scared of cats\index{cat} and dogs\index{dog}.
我尝试使用 grep 和 sed 的一些命令,但没有成功。任何帮助都非常感谢。
我试过:
cat story.tex | grep "^.*" animals.tex | sed "s/.*$/&/" > story2.tex
没有成功。
答案1
输入文件:
$cat file.txt
cats\index{cat}
dogs\index{dog}
elephants\index{elephant}
rats\index{rat}
$cat animals.tex
elephants are afraid of rats but are not scared of cats and dogs.
cats eat rats but elephants don't eat dogs
代码:
use strict;
use warnings;
open my $fh1, '<', 'file.txt' or die "unable to open 'file.txt': $!";
my %keyval;
while(<$fh1>) {
chomp;
$keyval{$2} = $1 if /^((.+?)\\.+)$/;
}
open my $fh2, '<', 'animals.tex' or die "unable to open 'animals.tex': $!";
open my $fout, '>', 'story2.tex' or die "unable to open 'story2.tex': $!";
while(my $line = <$fh2>) {
while(my ($k,$m) = each %keyval) {
$line =~ s/$k/$m/g;
}
print $fout $line;
}
输出文件:
$cat story2.tex
elephants\index{elephant} are afraid of rats\index{rat} but are not scared of cats\index{cat} and dogs\index{dog}.
cats\index{cat} eat rats\index{rat} but elephants\index{elephant} don't eat dogs\index{dog}