I want to replace \emph{G. fortis} with \emph{G. fortis}\index{\emph{Geospiza fortis}} to add terms to an index in a TeX document. I have a list of words in a file called gfortis that I will pass through the sed command in a while read -r command. 
PREFTXt="\emph{G. fortis}" # text to search
REPLACETXT="$PREFTXt\index{\emph{Geospiza fortis}}" # text to replace
sed -e "s/${PREFTXt}/${REPLACETXT}/" path/chapt1.tex
The result is this:
\emph{G. fortis}index{emph{Geospiza fortis}}
But it should be:
\emph{G. fortis}\index{\emph{Geospiza fortis}}
The final command looks like that:
while read -r RP 
do
echo "Adding $RP to the index"
PREFTXt="$RP"
ADDTXt="\index{\emph{Geospiza fortis}}"
REPLACETXT="$PREFTXt$ADDTXt"
echo "Replaced $RP with $REPLACETXT"
sed -e "s/${PREFTXt}/${REPLACETXT}/" path/chapt1.tex # should replace the text within this file. 
done < path/words_index/gfortis # input the words file to replace with a certain \index command 
The cap1.txt contains this:
\chapter{Another chapter in the wall}
NICE other\index{other} to be added to the index. 
\emph{Geospiza fortis}
All of the stuff that I put here shall be into the index. 
\emph{Geospiza fortis}
This index will be gigantic, but I won't be making multiple indexes. 
\emph{G. fortis} 
Other cool stuff here 
\emph{G. fortis} 
I'm using bash in macOS Mojave
 
     
    