Conditional replace in vim

喜欢而已 提交于 2019-11-30 04:47:48

问题


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.



来源:https://stackoverflow.com/questions/17337979/conditional-replace-in-vim

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!