Replacing quotation marks with “``” and “''”

吃可爱长大的小学妹 提交于 2019-12-01 23:26:14

Here's my one-liner using repeated sed's:

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

(note: it won't work correctly if there are already back-ticks (`) in the file but otherwise should do the trick)

EDIT:

Removed back-tick bug by simplifying, now works for all cases:

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

With comments:

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 "

This is my one-liner which is works for me:

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

And there is long version of this one-liner with comments:

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

You may run this script by:

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

Using awk

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

Explanation

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

Using sed

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

This might work for you:

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

Explanation:

  • Make a copy of the original line h
  • Replace pairs of "'s s/"\([^"]*\)"/``\1''\'\''/g
  • Check for odd " and if found revert to original line /"/g
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!