replace keywords in a file by keywords\index{keywords} from a list file

2

I am trying to produce index entries in a LaTeX file under Linux. I have two files: file1.txt has all the index entries

cats\index{cat}
dogs\index{dog} 
elephants\index{elephant}
rats\index{rat}

The animals.tex file contains the story text.

elephants are afraid of rats but are not scared of cats and dogs.

How can I replace the different animals in the .tex file with the ones of the file1.txt? to get the following text:

Elephants\index{elephant} are afraid of rats\index{rat} but are not scared of cats\index{cat} and dogs\index{dog}.

I have tried some commands with grep and sed, but I was not successful. Any help is much appreciated.

I tried:

cat story.tex | grep "^.*" animals.tex | sed "s/.*$/&/" > story2.tex

No success.

yacine

Posted 2019-11-30T15:57:56.190

Reputation: 23

Are you OK for a perl solution? – Toto – 2019-12-01T12:00:33.800

Answers

1

Input files:

$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

Code:

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;
}

Output file:

$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}

Toto

Posted 2019-11-30T15:57:56.190

Reputation: 7 722

Thank you very much for your answe @Toto ! I worked seamlessly. I had some UTF8 characters in my text. So, I added `use utf8' after the 3rd line. – yacine – 2019-12-01T17:43:31.133

@yacine: You're welcome, glad it helps. – Toto – 2019-12-01T17:50:05.987

I need to take some time to digest it! – yacine – 2019-12-01T18:27:37.473

@yacine: No problems. You can consider upvoting – Toto – 2019-12-01T19:57:50.547