Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I am helping a friend with her thesis written in LaTeX and I need a quick solution for a "search and replace". Using a terminal in Linux, how can I find the following pattern:

\caption{*\cite{*}}

and replace \cite with \protect\cite

I was using Kate. Using its search feature I initially found more than 2000 hits and by refining my search I narrowed it down to some 300 hits. However I need to narrow it down further because I do not want to replace all \cite. I only want to replace \cite if it occurs within \caption{}

share|improve this question

1 Answer 1

Assuming the caption and citation text do not contain special characters (in particular, the first * in your example should not contain \ and the second * should not contain }) then a GNU sed regex

s:(\\caption\{[^\]+)(\\cite\{[^}]+\}\}):\1\\protect\2:g

should work, I think. If there may be empty caption and/or citation strings you may want to change the + modifiers to *. You can test it without modifying the file(s) using

sed -nr 's:(\\caption\{[^\]+)(\\cite\{[^}]+\}\}):\1\\protect\2:gp' files

If that seems to find and modify the right instances, then you can make it modify the files in-place using the -i option - if you are not already working on separate copies you can make backups automatically

sed -i.bak -r 's:(\\caption\{[^\]+)(\\cite\{[^}]+\}\}):\1\\protect\2:g' files

Similar expressions are possible in perl if sed doesn't work for you. Other versions of sed should work but may need different escaping of the special characters.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.