sjkblog

Replace quotation marks using Perl

Posted on 05 Dec 2012.

Quotations in LaTeX should start with `` and end with ''. LaTeX will format these according to babel settings et.c. When pasting text from websites, Word documents, or similar into your LaTeX documents, "quotations like this one" can easily sneak into your document unnoticed and cause strange errors.

To replace "this" with ``this'', use the following perl one liner:

perl -0777 -pi.orig -e 's/"([^"]+)"/\x60\x60\1\x27\x27/g' *.tex

Habbie suggested using \x60 and \x27 to avoid escape trouble, and -0777 to make it work with multiple line quotations.

Update: xkr47 suggests using "(.*?)" together with the s modifier, to save some typing:

perl -0777 -pi.orig -e 's/"(.*?)"/\x60\x60\1\x27\x27/gs' *.tex

Update 2: bairui of #vim, Freenode, explains that this can be done from within vim using the following regular expression:

:%s/"\(\_.\{-}\)"/``\1''/g

Sweet! I decided to create an 'alias' for it in vim, and added the following to my .vimrc:

command FixQuotes :%s/"\(\_.\{-}\)"/``\1''/g

Typing :FixQuotes in normal mode executes the substitution command.

blog comments powered by Disqus