简体   繁体   中英

Regex - replace every odd/even occurrence

OK, guys, the task is to replace every odd occurrence of a pattern A with pattern B and every even occurrence with pattern C. I gave up on this and wrote a python script for the task but I was wondering if it can be handled with regular expression replacement (via eg. sed or vi)

If you need to know what purpose this is for, it is to reformat a long text with double quotes to the LaTeX style (`` opens, '' closes).

Most straightforwardly by reading the file fully into the pattern space before working on it -- since it's a LaTeX source file, I assume that it fits into memory comfortably. You might use

sed ':a $!{ N; ba }; s/"\([^"]*\)"/``\1'"''"'/g' filename.tex

Shell quoting of the '' (LaTeX closing quotes) makes this look more confusing than it is. What sed sees is

:a $!{ N; ba }          # read the whole file into the pattern space
s/"\([^"]*\)"/``\1''/g  # replace all quoted strings with LaTeX-quoted strings

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM