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.
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.
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).
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.
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.
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:
:%s/find/replace/gc
n
, interrupt the search by pressing <ctrl-C>
<shift-N>
to go back to the previous occurrence of your find
term:.,$s/find/replace/gc
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With