我正在尝试在 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}