Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I switch from forward to backward in Interactive search/replace regex in Vim?

Tags:

vim

For example I have some text:

    'y'     to substitute this match
    'l'     to substitute this match and then quit ("last")
    'n'     to skip this match
    <Esc>   to quit substituting
    'a'     to substitute this and all remaining matches {not in Vi}
    'q'     to quit substituting {not in Vi}

and by :%s/substitute/sub/gc I can interactively search/replace. If I press 'n' it goes to the next matched pattern, how can I undo 'n'? or search backwards?

In usual search mode /search_word we can skip by 'n' and 'N' is there something similar for substitute - :%s/substitute/sub/gc ?

like image 910
whitesiroi Avatar asked Aug 12 '15 05:08

whitesiroi


People also ask

How do I go to previous in vi?

Press <shift-N> to go back to the previous occurrence of your find term.

What is CGN in Vim?

We can then type in the cgn command combo: cgn. This Vim editor command finds the last thing we searched for, delete it, and then put us into insert mode. While in insert mode, let's type in the word “tutorial”.

How do you change multiple words in Vim?

Change and repeat Search for text using / or for a word using * . In normal mode, type cgn (change the next search hit) then immediately type the replacement. Press Esc to finish. From normal mode, search for the next occurrence that you want to replace ( n ) and press . to repeat the last change.


2 Answers

Mathias Bergert's answer does the trick, if you just need do simple single word replacement, and the replacement text is always fixed. Well perhaps this is satisfied with 70% of our daily editing. If you need the power of s/.../.../ for your substitution needs, it may be not sufficient. For example, multiple words replacement, the back reference or the function expressions in the replacement part.

What I can think of is, first do a:

:s/substitute/sub/c

note, without % range and g flag.

then you just:

  • press n or N for for/backwards search,
  • if you think the match should be replaced, press &,
  • if you did some mistake, press u

The key is, & will redo last substitution.

In this way, you can do more complex substitutions, which is hard for the simple cw like:

  • s/f../&, / add a comma after all fxx words (foo, far, fur...)
  • s/\v(foo)(\d+)/\=submatch(1).(submatch(2)+1)/ increment number after foo
  • and so on...
like image 112
Kent Avatar answered Sep 27 '22 22:09

Kent


Personally I prefer the . command over the substitute c flag, this adds much more flexibility.

Do something like this:

/substitute<cr>
cwsub<esc>

Search for "substitute", then cw (change word) to "sub" (<esc> exits insert mode)

Now you can use n and N to move and the dot . command to replace the "substitute" to "sub". With u you can even undo the last one.

like image 28
Mathias Begert Avatar answered Sep 27 '22 22:09

Mathias Begert