Thursday, April 17, 2008

Easier Search + Sub

I can't say how many times I've tried to work out a complex substitute command in Vim only to have the pattern fail and not match what I wanted. I've recently come across an easier way to accomplish a substitution on a pattern that's already guaranteed to match. Say you have the following data in your editor.

"this is a line 12345"

Execute a search (instead of a sub):
" match digits
/\d\+

Now execute a sub with no pattern:

%:s//7890/g

The result would be:

"this is a line 7890"

Obviously this is a simple example, but I find this technique handy whenever I'm working out complex patterns.

3 comments:

Michael A. Plikk said...

When doing this it also helps to have both search result highlighting (:set hls) and incremental search highlighting (:set incsearch) on. That way you'll see what your pattern matches as you type it, and once it is typed you quickly get an overview of what will be changed in the coming search+replace :)

Charles-Henri said...

This blog really rocks !!!
I am using vim since a long time every day. I considere my self as an advanced user.
But I still learn about vim every day too, even simple tricks such as this one :-)

Thank you very much and keep going, please :-)

Travis Whitton said...

@ michael

Yup, top of my vimrc

set ic is hls

Good call though, it makes searching a lot easier.

@charles

Glad you're liking the blog. Feel free to contribute, and I'll keep the tips coming.