Conditional replace in vim

2019-02-17 08:22发布

问题:

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:

:s/\("\|'\)/\1=="?':"/

Where of course the \1=="?':"-part is something that works in vim.

Thanks in advance!

回答1:

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.)



回答2:

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('.'), "'\"", "\"'"))


回答3:

power of unix tools ;)

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



回答4:

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.



回答5:

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.



标签: vim vi