5

I'd like to replace the entire buffer (file) with the current search range selection:

:/pattern1/;,/pattern2/p

How this can be achieved?

  • Do you mean :/pat1/;/pat2/d | %d_ | put | 1d, or do you mean reusing the previous range (which can't be done aside from using the history, AFAIK)? – Antony Dec 21 '16 at 20:05
  • @Antony: Yes, I mean the 1st example of yours. Removing everything else apart of the content of current search range. If you could post it as the answer, would be great. – kenorb Dec 22 '16 at 0:31
6

One way to do this is to delete the range you are interested in, delete the remainder of the buffer into the black hole register, then put the text you want to keep into the empty buffer:

:/pat1/;/pat2/d | %d_ | put | 1d

The final 1d is to tidy up the empty line at the top, and handily leaves the cursor at the start of the buffer.

2

I couldn't find a straightforward solution, but a possible workaround is the following. Consider that you have the following buffer and you want to keep the lines dolor to amet:

Lorem
ipsum
dolor
sit
amet
consectetur
adipiscing
elit

First, mark the lines you want to keep:

:/pattern1/,/pattern2/norm! AXXX

Here that would be /dolor/,/amet/norm! AXXX and you would get:

Lorem
ipsum
dolorXXX
sitXXX
ametXXX
consectetur
adipiscing
elit

Delete the lines which wasn't marked:

:g!/XXX/d

You would get:

dolorXXX
sitXXX
ametXXX

Now you have only the lines you wanted, remove the marks:

:%s/XXX$//

You'll get:

dolor
sit
amet

Of course it is possible to wrap that into a function:

function! RemoveOtherLines(pattern1, pattern2)
    execute '/' . a:pattern1 . '/,/' . a:pattern2 . '/norm! AXXX'
    execute 'g!/XXX/d'
    execute '%s/XXX$//'
endfunction

But maybe you'll get some problems with some escaped patterns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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