问题
I'm editing a book in LaTeX and its quotation marks syntax is different from the simple "
characters. So I want to convert "quoted text here"
to ``quoted text here''
.
I have 50 text files with lots of quotations inside. I tried to write a regular expression to substitute the first "
with ``
and the second "
with ''
, but I failed. I searched on internet and asked some friends, but I had no success at all. The closest thing I got to replace the first quotation mark is
s/"[a-z]/``/g
but this is clearly wrong, since
"quoted text here"
will become
``uoted text here"
How can I solve my problem?
回答1:
I'm a little confused by your approach. Shouldn't it be the other way round with s/``/"[a-z]/g
? But then, I think it'll be better with:
s/``(.*?)''/"\1"/g
(.*?)
captures what's between ``
and ''
.
\1
contains this capture.
If it's the opposite that you're looking for (i.e. I wrongly interpreted your question), then I would suggest this:
s/"(.*?)"/``\1''/g
Which works on the same principles as the previous regex.
回答2:
Use the following to tackle multiple quotations, replacing all "
in one step.
echo '"Quote" she said, "again."' | sed "s/\"\([^\"]*\)\"/\`\`\1''/g"
The [^\"]*
avoids the need for ungreedy matching, which does not seem possible in sed.
回答3:
Try grouping the word:
sed 's/"\([a-z]\)/``\1/'
On my PC:
abhishekm71@PC:~$ echo \"hello\" | sed 's/"\([a-z]\)/``\1/'
``hello"
回答4:
It depends a little on your input file (are quotes always paired, or can there be ommissions?). I suggest the following robust approach:
sed 's/"\([0-9a-zA-Z]\)/``\1/g'
sed "s/\([0-9a-zA-Z]\)\"/\1\'\'/g"
Assumption: An opening quotation mark is always immediately followed by a letter or digit, a closing quotation mark is preceeded by one. Quotations can span over several words an even several input lines (some of the other solutions don't work when this happens).
Note that I also replace the closing quotation mark: Depending on the fonts you use the double quotation mark can be typeset as neutral straight quotation mark.
来源:https://stackoverflow.com/questions/22173498/change-quotation-marks-to-latex-style