Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

If I type /regex then the cursor temporarily jumps to the first match and all matches are highlighted. This updates as I type. Is it possible to get this behavior when I'm getting ready to make a substitution? For instance, when I'm working on a complicated regular expression :%s/\<regex\>/, I would like to know what is matching before I pull the trigger and change everything. Any way to do it?

share|improve this question
add comment

3 Answers 3

up vote 8 down vote accepted

Type your search using / (or ?) to begin with, which will allow you to tweak your regex (since you're using incsearch)

Once you get it all nice, you can use the previous search pattern (the one you just used) in the substitute command by using two separators for the 'search' item:

/elephant                       " find the next elephant
:%s//rhino/gc                   " make then all rhinos!

Of course, you can use selections and ranges, as normal.

:1,15s,,cougar,g
:'<,'>s::tiger:
share|improve this answer
    
+1 for teaching me about s// –  Steven Lu Jul 17 '13 at 15:36
add comment

One option is that you can have a confirmation flag c.

:%s;regex;replacement;gc

:h s_flags:

[c] Confirm each substitution.  Vim highlights the matching string.  You can type:              
        '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
        'q'     to quit substituting

You can also try grep command to see the filtered output and the highlighted original file.

:g/re/p or :g/re/

share|improve this answer
    
I like it, but it still require me to complete the regular expression before I see what if anything was matched. –  John Berryman Jun 12 '12 at 17:41
add comment

Well, the short way to see what your regular expression will match is doing a search with / using your desired regex. It will jump to the first match and mark it up while your're typing it. Try it - vim will not disappoint you.

share|improve this answer
    
True, though that's what I stated in the question. I wish it would update as I'm getting ready to substitute. With your solution I have to try the regex and then copy it (how?) and then use it in a substitution. That's not good enough. –  John Berryman Jun 13 '12 at 19:48
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.