Monday, October 25, 2021

[SOLVED] Adding parenthesis around all equation numbers using sed

Issue

I have a big LaTeX file containing huge loads of equations. They are all referenced as follows:

Equation~\ref{XX}
Equation~\ref{XY}
...

I want to obtain this,

Equation~(\ref{XX})
Equation~(\ref{XY})
...

I have only a basic knowledge of sed, but I'm convinced it could do the trick using the '&' symbol.

I tried:

sed 's#\ref{*}#(&)#g' input_tex_file.tex

Which does not change anything.

If I do:

sed 's#\ref{XX}#(&)#g' input_tex_file.tex

I obviously obtain

Equation~(\ref{XX})

But I would like to avoid writing a script to detect all references and modify them sequentially, even if I guess it would not be overwhelming.

Please also note that I have loads of things like Table~\ref{XX} and Figure~\ref{XX} that I would like to left unmodified.

Any ideas ?


Solution

The & symbol in the replacement pattern stands for the whole match. You seem to wannt to avoid modifying values after any word but Equation~, so it should be included into the pattern and that means, you cannot use &, but regular \1 and \2 to refer to captured parts of the regex.

You may capture the Equation~ and the rest of the pattern into two separate groups and refer to them in the replacement:

sed 's#\(Equation~\)\(\\ref{[^{}]*}\)#\1(\2)#g'

or, with POSIX ERE,

sed -E 's#(Equation~)(\\ref\{[^{}]*})#\1(\2)#g'

Demo:

s='Equation~\ref{XX} Table~\ref{XX} and Figure~\ref{XX}'
echo "$s" | sed 's#\(Equation~\)\(\\ref{[^{}]*}\)#\1(\2)#g'
# => Equation~(\ref{XX}) Table~\ref{XX} and Figure~\ref{XX}


Answered By - Wiktor Stribiżew