Conditional replace in vim

后端 未结 5 582
渐次进展
渐次进展 2021-01-05 01:10

I\'d like do use vim search-and-replace to replace all \" with \' and vice-versa. Is there a way to achieve this in one step? I\'m thinking of something like this:

相关标签:
5条回答
  • 2021-01-05 01:21

    That's a case for :help sub-replace-special:

    :s/["']/\=submatch(0) == '"' ? "'" : '"'/g
    

    This matches any of the two quotes (in a simpler way with [...]), and then uses the ternary operator to turn each quote into its opposite. (For more complex cases, you could use Dictionary lookups.)

    0 讨论(0)
  • 2021-01-05 01:22

    You can do so easily by using the abolish.vim plugin.

    Abolish.vim has a :Subvert command which gives you a different approach to searching and replacing in its own little DSL.

    :%S/{\",'}/{',\"}/g
    

    This plugin has received the special honour of having a three-part screencast on Vimcasts.org dedicated to it: one, two, three.

    0 讨论(0)
  • 2021-01-05 01:29

    Probably the laziest/easiest way:

      :%s/'/__/g | %s/"/'/g | %s/__/"/g
    

    Three basic steps combined into one line:

    1. convert ' to __ (or something random)
    2. convert " to '
    3. convert __ to "

    Then combine them with the | symbol.

    I'm sure some vim wizards will have a better solution, but that worked for me.

    0 讨论(0)
  • 2021-01-05 01:33

    power of unix tools ;)

    :%!tr "'\"" "\"'"

    0 讨论(0)
  • 2021-01-05 01:35

    Another approach (that's more suited to scripting) is to use the built-in tr() function. To apply it on the buffer, getline() / setline() is used:

    :call setline('.', tr(getline('.'), "'\"", "\"'"))
    
    0 讨论(0)
提交回复
热议问题