1

I often find myself doing

:s/foo/bar/g
*move to different line*
:s/bar/foo/g

on different lines. Is there an easy way to swap them around so that I can execute the second version quickly?

3
  • Do you want to swap to strings around? The example you gave seens to do "nothing" sice "foo" will be "foo" after the replacement. Commented Jan 17, 2012 at 12:43
  • I've edited it to make it clearer. I'd like to do one find and replace somewhere and then one the reverse of it somewhere else. It happens reasonably often to me... Commented Jan 17, 2012 at 13:16
  • possible duplicate of this Commented Jan 17, 2012 at 13:24

3 Answers 3

2

You could try the Abolish plugin (git homepage):

 :Subvert/{foo,bar}/{bar,foo}/g

Without plugin:

 :%s/foo\|bar/\=submatch(0) ==# 'foo' ? 'bar' : 'foo'/g
Sign up to request clarification or add additional context in comments.

Comments

2

The quick use once only option is to do the following

:s/~/<c-r>//g<cr>

~ matches the last substitution and <c-r>/ will insert the current search string from the "/ register. Therefore flipping the substitution. A word of warning is that ~ can only be used once because after the substitution it will be changed. Also doing a search between substitutions will result in the "/ register changing.

As an alternative you could try to use the command-line window to edit the command like text in any other window.

Use q: to open the command-line window from normal mode or press ctrl-f from the command line (assuming the default setting for 'cedit').

Drew Neil has a vimcasts episode that deals with refining search patterns via the command-window which is similar.

:h /~
:h c_CTRL-R
:h quote/
:h cmdwin
:h q:
:h 'cedit'

Comments

1

You can use dict in vim

:%s/foo\|bar/\={'foo':'bar', 'bar':'foo'}[submatch(0)]/g

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.