Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting / changing searched text in Vim

When I do an interactive search for some pattern, each time I hit n, I get the next result. How do I delete / change each result that I come to?

Ideally, what I'm looking for would work like this: I hit n to get the search result, and then magic command to highlight that result in visual mode, and then I can do d or c to delete or change the highlighted text.

Example:

I enter the command

/hello .

and it matches hello, a space, and any character after it.

So say the first match it reaches is "hello w".

Now, I want to delete all of hello w, search for the next match (say it is hello a), change the next match to hello there, and keep doing different things to each match.

I'm not looking for just search-and-replace, because I want to be able to perform any action on each result interactively, such as delete the first result, replace the second result with bye, and replace the third result with later.

like image 567
Chetan Avatar asked Oct 21 '10 04:10

Chetan


People also ask

How do you do search and delete in Vim?

You can also just search using /phrase , select the next match with gn , and delete it with d .


2 Answers

To select the entire match of the current match (if you are at the start of the match) you can type

v//e

To delete to the end of the match

d//e

To change the match

c//e

Only negative is that you cant use n (as that will redo //e ) and instead have to use //

So typical workflow would look like this

/hello ./    : Jump to the start of the next "hello ."
d//e         : Delete the item
//           : repeat the search to get to the begining of the next "hello ."
c//e         : change it
//           : next one.
etc.
like image 152
Michael Anderson Avatar answered Oct 28 '22 02:10

Michael Anderson


I think you want gn: (Go to the next match and) select it in visual mode. You can prefix this with a command, e.g. cgn changes the match, dgn deletes etc. I found that if already on a match, this match is used, so that this should do it.

like image 34
srs Avatar answered Oct 28 '22 02:10

srs