I'm formatting a long document with many chapters. Most chapters contain some generic sections (e.g. "Introduction," "Results," …) and most of them are already labeled accordingly (e.g. \label{sec:intro}
, \label{sec:results}
). This is fine on a chapter-by-chapter basis, but when I put them all together, it means some labels will be used more than once (e.g. there might be five sec:intro
labels from five different chapters.)
Can I use these labels without re-naming them? Is LaTeX smart enough to know that within the .tex
file for chapter 2, \ref{sec:intro}
refers to the "Introduction" section in the current chapter.
If not, what's the preferred solution? Renaming all the labels seems clunky and brittle.
Best Answer
As David Carlisle says, rename your labels. This can easily be done using the Stream Editor,
sed
for example.Let's say that you have one chapter file about Lions, and one about Zebras; in both chapter files you have used the labelling convention you described, something like the following:
lions.tex
zerbras.tex
You can use
sed
to search and replace each\label
and\ref
in each of the files so that all of your labels and references change appropriatelyNow your files look like the following
lions.tex (new)
zebras.tex (new)
Understanding \(label\|ref){([^}]*)/\\1{lions:\2/g
The basic syntax I have used is
s/old/new/g
to substitute 'old' with 'new'. Theg
flag says to do it globally. Let's break the above expression down into parts:\\\(label\|ref\)
matches\label
or\ref
and stores the result into memory, to be used later as\1
. Note that we need to use a\
to escape special characters{\([^}]*\)
matches the stuff inside{...}
, but does so in a non-greedy way. It is very important for this regexp not to be greedy; if were greedy, then when operating upon the expressionHere's a reference to \ref{sec:intro} and \ref{sec:results}
it would matchsec:intro} and \ref{sec:results}
which is not what we intend!
\\\1{lions:\2
is the replacement text, using\1
and\2
as the match that has been stored into memory.