Wednesday, July 29, 2009

Vim Non-Greedy Search

Just a self-post here to help serve as a reminder that the non-greedy search operator for vim is .\{-} instead of the .*? in most languages. This was useful when attempting to replace bad image paths for a template file that contained lots of images that were hosted on various servers and I wanted to consolidate them to get around security warnings. The search command string in vim then ends up as:
:/src=\".\{-}\.\(gif\|png\|jpg\)\"/
This can be combined with a search and replace command as:
:%s/src=\".*\(\/.\{-}\.\(gif\|png\|jpg\)\)\"/src=\"myimagelocation\1\"/gc
Oh, and a super nice thing to know is that you can copy and paste from the cmd line in vim by hitting ctrl-f to open a new cmd window. This is great for saving thost extremely wordy vim regexes that you need to type over and over.

3 comments:

  1. Is this a Kearns guest post? Or it must be work for Kearns. When the hell did you start using vim?

    (and don't forget those "jpeg" files too)

    ReplyDelete
  2. Nope, I'm using Vim all by myself at work. I have found it to be ridiculously useful for regex find and replace in a single file and in multiple files. It's a HUGE learning curve, but I'm able to do some pretty cool tricks that would have taken me a long time in other IDEs. It works really well on extremely large files that would cause other IDEs to choke.

    ReplyDelete
  3. @Kooshmoose: thanks a lot man... I was desperately searching for this!

    ReplyDelete