Tuesday, November 22, 2011

Re: How to find/delete block between matching lines?

On 11/22/11 06:08, Jürgen Krämer wrote:
>> I want to find blocks of text from a line matching my first
>> regex up to a line matching my second regex. I'd like to be
>> able to include or exclude the matching lines and I'd love
>> to be able to execute a deletion or other command on such
>> the found blocks.
>
> This will only the next block. If you want to delete all
> block, prefix the command with "g":
>
> :g/first regex/+1;/second regex/-1d

I want to second Jürgen's suggestion here--I use it rather
frequently and it's one of the things that makes Vim blow just
about every other editor out of the water. Study it until it
makes sense and then you'll find all manner of places you can use
it. To break it down, it's

:g/first regex/<range><command>

to execute <command> for every <range> around a match for "first
regex". That range can even include backwards searching such as

:g/re1/?re2?+1;/re3/-1d

which will search for "re1", search backwards for "re2", move
forward a line to start the range, and then search forward for
"re3" and move back a line for the end of the range, and then
delete the contents. I've done this on files with 10k+ lines
where I wanted to find sections containing certain data and
delete everything else. With another editor, I'd have either
spent HOURS on it, or had to resort to some sort of
sed/awk/perl/python scripting solution. In Vim, it took less
than 30 seconds.

-tim


--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

No comments: