Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all paragraphs where a pattern is not present?

Tags:

vim

I keep a log-book of the meetings in which I took part.

Each meeting :

  • is separated by a blank line (-> each meeting is a paragraph)
  • is folded thanks to an expression
  • contains a line with the corresponding tags : ACME, GMBH, SARL, etc…

When I want to make a review of all the meetings I had with, e.g., ACME,

  • I create a scratch buffer (:%y, followed by :tabnew, followed by paste)
  • and I wish to eliminate all paragraphs where ACME does not figure.

This is where I have a problem.

I know how to search/delete by lines :

:v/ACME/d

But how do I do that by paragraph (so as to keep the whole paragraph where ACME figures, and not the only line of tags) ?

NB : the pattern ACME can figure more than once in those paragraphs.

like image 822
ThG Avatar asked Aug 29 '13 09:08

ThG


People also ask

How do you get rid of paragraph marks in Word that won't delete?

You can remove paragraph marks in Word by using the 'Find' and 'Replace' commands, which are present on the right side of the 'Home' tab. Alternatively, you can use 'Ctrl+F' for 'Find' and 'Ctrl+H' for 'Replace.

How do you backspace an entire paragraph?

Open the document in Microsoft Word or another word processor. Move the mouse cursor to the beginning of the line of text you want to delete. Press and hold the left mouse button, then drag the mouse to the right until the entire line of text is highlighted. Press Backspace or Delete to delete the line of text.


2 Answers

This works:

let @r="" | execute("g/acme/ normal \"Rdap") | %d | put r

It goes to every paragraph containing "acme", and delete it appending to register r. Then deletes everything and puts register r.

As you see, basic trick is using capital letter register to add to it, instead of replacing its content. This also requires resetting the register at the beginning, to discard previous register contents.

This works ok for paragraphs with multiple occurrences of "acme", as the whole paragraph is deleted after the first match, and so, it's not matched again.

like image 110
elmart Avatar answered Sep 21 '22 08:09

elmart


I would do it with awk, in vim you could:

%!awk -v RS="" -v ORS="\n\n" '/ACME/' 

then only paragraphs containing ACME will be kept.

like image 35
Kent Avatar answered Sep 21 '22 08:09

Kent