Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to go back to previous when doing find replace confirm in vi?

Tags:

vim

vi

Frequently when I am doing a find and replace in vi I will do it like this:

:%s/find/replace/gc

This gives you the option to skip by pressing n, or replace by pressing y. But, sometimes I will accidentally skip over one in a large file by pressing n when I meant to press y.

How do I go backwards to the previous one and give me a second change?

Essentially, how to I find (search) the other direction temporarily? thanks.

like image 429
makansij Avatar asked Jun 10 '17 01:06

makansij


People also ask

How do I go to previous search in vi?

vi positions the cursor at the next occurrence of the string. For example, to find the string “meta,” type /meta followed by Return. Type n to go to the next occurrence of the string. Type N to go to the previous occurrence.

How do I go back to the previous line in Vim?

To jump back to line # 300 or previous position press CTRL-O (press and hold Ctrl key and press letter O). To jump back forwards press CTRL-I (press and hold Ctrl key and press letter I).

How do we search for old and replace it with new in Vim?

It's simple to search and then decide if you want to keep or replace each result in a file: Execute a regular search with / . Use the keystroke cgn on the first result to replace it. Type n or N to go to the next result.

How do I replace a word in vi editor?

The simplest way to perform a search and replace in Vim editor is using the slash and dot method. We can use the slash to search for a word, and then use the dot to replace it. This will highlight the first occurrence of the word “article”, and we can press the Enter key to jump to it.


1 Answers

I'm not sure if you would like to interrupt current find-replace operation and resume it again. But if that is acceptable, here is my suggestion:

  1. Start your find-replace the way you mentioned: :%s/find/replace/gc
  2. After you accidentally skip over a substitution by pressing n, interrupt the search by pressing <ctrl-C>
  3. Press <shift-N> to go back to the previous occurrence of your find term
  4. Run find-replace a little differently while you are at this word: :.,$s/find/replace/gc
  5. Continue the operation

All this functionality works with vim native capabilities without having to install any addon.

Note: The .,$ range specifier indicates to perform :s (substitute) operation over a range of lines that start with current line (indicated by .) and until last line (indicated by $).

Note2: It might be known to you, but reiterating for anyone else who stumbles upon this post searching for something similar - The % range specifier indicates to perform :s (substitute) operation over all lines of currently active buffer.

like image 123
Prasanna Avatar answered Oct 10 '22 02:10

Prasanna