用“`”和“''”替换引号

时间:2012-01-23 03:56:34

标签: bash quotes tex

我有一个包含许多"标记的文档,但我想将其转换为在TeX中使用。

TeX使用2个标记作为开头引号,2'标记结束引号。

我只想在"出现在偶数的单行上时对其进行更改(例如,行上有2个,4个或6个")。例如,

"This line has 2 quotation marks."
--> ``This line has 2 quotation marks.''

"This line," said the spider, "Has 4 quotation marks."
--> ``This line,'' said the spider, ``Has 4 quotation marks.''

"This line," said the spider, must have a problem, because there are 3 quotation marks."
--> (unchanged)

我的句子永远不会跨越行,因此无需检查多行。

引用单引号的引号很少,因此我可以手动更改它们。

我该如何转换这些?

4 个答案:

答案 0 :(得分:3)

这是我的单行,对我有用:

awk -F\" '{if((NF-1)%2==0){res=$0;for(i=1;i<NF;i++){to="``";if(i%2==0){to="'\'\''"}res=gensub("\"", to, 1, res)};print res}else{print}}' input.txt >output.txt

这个单行的长版本有评论:

{
    FS="\"" # set field separator to double quote
    if ((NF-1) % 2 == 0) { # if count of double quotes in line are even number
        res = $0 # save original line to res variable
        for (i = 1; i < NF; i++) { # for each double quote
            to = "``" # replace current occurency of double quote by ``
            if (i % 2 == 0) { # if its closes quote replace by ''
                to = "''"
            }
            # replace " by to in res and save result to res
            res = gensub("\"", to, 1, res)
        }
        print res # print resulted line
    } else {
        print # print original line when nothing to change
    }
}

您可以通过以下方式运行此脚本:

awk -f replace-quotes.awk input.txt >output.txt

答案 1 :(得分:2)

使用awk

awk '{n=gsub("\"","&")}!(n%2){while(n--){n%2?Q=q:Q="`";sub("\"",Q Q)}}1' q=\' in

<强>解释

awk '{
  n=gsub("\"","&") # set n to the number of quotes in the current line
}
!(n%2){ # if there are even number of quotes
  while(n--){ # as long as we have double-quotes
    n%2?Q=q:Q="`" # alternate Q between a backtick and single quote
    sub("\"",Q Q) # replace the next double quote with two of whatever Q is
  }
}1 # print out all other lines untouched' 
q=\' in # set the q variable to a single quote and pass the file 'in' as input

使用sed

sed '/^\([^"]*"[^"]*"[^"]*\)*$/s/"\([^"]*\)"/``\1'\'\''/g' in

答案 2 :(得分:2)

这是我使用重复sed的单行代码:

cat file.txt | sed -e 's/"\([^"]*\)"/`\1`/g' | sed '/"/s/`/\"/g' | sed -e 's/`\([^`]*\)`/``\1'\'''\''/g'

(注意:如果文件中已经存在反向标记(`),它将无法正常工作,否则应该执行此操作)

修改

通过简化删除后退错误,现在适用于所有情况:

cat file.txt | sed -e 's/"\([^"]*\)"/``\1'\'\''/g' | sed '/"/s/``/"/g' | sed '/"/s/'\'\''/"/g'

评论:

cat file.txt                           # read file
| sed -e 's/"\([^"]*\)"/``\1'\'\''/g'  # initial replace
| sed '/"/s/``/"/g'                    # revert `` to " on lines with extra "
| sed '/"/s/'\'\''/"/g'                # revert '' to " on lines with extra "

答案 3 :(得分:2)

这可能对您有用:

sed 'h;s/"\([^"]*\)"/``\1''\'\''/g;/"/g' file

说明:

  • 制作原始行h
  • 的副本
  • 替换成对的" s/"\([^"]*\)"/``\1''\'\''/g
  • 检查奇数",如果找到,则恢复为原始行/"/g