sponsor Vim development Vim logo Vim Book Ad

intermediate Tip #578: Specify Range with search patterns

 tip karma   Rating 23/17, Viewed by 915 

created:   October 5, 2003 22:48      complexity:   intermediate
author:   duvell      as of Vim:   6.0

I was recently using sed to pull out multi-line fields with sed when I wondered if I could specify a range using two search patterns in vim as I can in sed.  Sure enough it works.  I am using 6.1 and do not know if this feature is new but I suspect it  has probably been around.

Here is a contrived example.  Suppose I had a vim script I was editing and I want to comment out the function declaration of a function named My_func.  Instead of searching for it, marking the range and then adding a comment to the start of the line, the following command will work:

:/^ *function *My_funct\>/,/^ *endfunction/s/^/" /

The range is specified by two patterns.  For the start of the range I look for the line which contains function My_funct.  I added the \> end of word delimeter to the pattern in case I had other functions that had names beginning with My_func.

The end of the range will be the first occurance of the second pattern, /^ *endfunction/ starting from where the first pattern was matched.

The two patterns are separated with a comma as any range would be and the command to perform on the range follows.  In this case a substitution, s/^/: / but it could be any command.

This has become useful and even though I have used vim for several years this was a new discovery for me.

 rate this tip  Life Changing Helpful Unfulfilling 

<<Access [email protected] using Newsgroup Reader | Cut&Paste; without too much newlines, eg. into WORD >>

Additional Notes

If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to [email protected] after searching the archive. Help Bram help Uganda.
Sponsored by Web Concept Group Inc. SourceForge Logo