Conditional replacement in vim

I would like to use vim search-and-replace to replace all s and vice versa. Is there a way to do this in one step? I am thinking of something like this:

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

Where, of course, \1=="?':" -Part is what works in vim.

Thanks in advance!

+6
source share
5 answers

This is the case for :help sub-replace-special :

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

This matches either of the two quotes (easier with [...] ), and then uses the ternary operator to turn each quote into its opposite. (For more complex cases, you can use the Dictionary search.)

+14
source

Another approach (more suitable for scripting) is to use the built-in tr() function. To apply it in the buffer, getline() / setline() :

 :call setline('.', tr(getline('.'), "'\"", "\"'")) 
+3
source

power of unix tools;)

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

+3
source

You can do this easily using the abolish.vim plugin.

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

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

This plugin was particularly honored to have a three-part screencast on Vimcasts.org dedicated to it: one , two , three .

+2
source

Perhaps the laziest / easiest way:

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

Three main steps combined in one line:

  • convert ' to __ (or something random)
  • convert " to '
  • convert __ to "

Then combine them with | .

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

0
source

Source: https://habr.com/ru/post/948202/


All Articles