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!
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.)
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('.'), "'\"", "\"'"))
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.
Probably the laziest/easiest way:
:%s/'/__/g | %s/"/'/g | %s/__/"/g
Three basic steps combined into one line:
- convert
'
to __
(or something random)
- convert
"
to '
- convert
__
to "
Then combine them with the |
symbol.
I'm sure some vim wizards will have a better solution, but that worked for me.