-1

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

M. Beausoleil
  • 3,141
  • 6
  • 29
  • 61
  • I think you want `EFTXt='\\emph{G\. fortis}'` and then `REPLACETXT='&\\index{\\emph{Geospiza fortis}}'`. See [demo](https://ideone.com/pMO2Bt). – Wiktor Stribiżew May 07 '20 at 14:47
  • Is there a way to do it literally. For example, would it be possible to use some sort of grep or something similar to prevent adding the ``\\`` or ``\.`` – M. Beausoleil May 07 '20 at 15:00

2 Answers2

0

You need to use a double backslash instead of a single one. This is because bash/shell etc. will interpret it as a special character and replace "\e" with "e".

To avoid having to escape those, you could put their contents in a file, for instance preftxt.cfg, and do something similar for the other file

it would contain

\emph{G. fortis}

And you could use it like this

PREFTXt="$(cat preftxt.cfg)"
axelduch
  • 10,769
  • 2
  • 31
  • 50
0

use 3 backslash \ instead of one -- \\\

REPLACETXT="$PREFTXt\\\index{\\\emph{Geospiza fortis}}"