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:


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{}


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


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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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