Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all lines matching a pattern and a line after in Vim?

Tags:

regex

vim

There's a text

Title of the text  This line contains a word that is matched by the pattern and it should be deleted. Next line is supposed to be deleted as well.  Loren ipsum dolorem...  This line contains a word that is matched by the pattern and it should be deleted. And this one should be deleted  The end of the article 

How to delete every pair of lines matching the first line, e.g. 'This line contains a word...' and the line after that one. Result would be:

Title of the text  Loren ipsum dolorem...  The end of the article 
like image 384
Boris Pavlović Avatar asked Apr 25 '13 19:04

Boris Pavlović


People also ask

How do I get rid of matching lines in Vim?

In order to delete lines matching a pattern in a file using vim editor, you can use ex command, g in combination with d command.

How do I delete a line not matching in Vim?

The ex command g is very useful for acting on lines that match a pattern. You can use it with the d command, to delete all lines that contain a particular pattern, or all lines that do not contain a pattern.

How do I delete all lines in vi?

Immediately after opening a file, type “gg” to move the cursor to the first line of the file, assuming it is not already there. Then type dG to delete all the lines or text in it.


2 Answers

You can use

:g/word/normal 2dd 

This finds all instances of word and then executes the command after it. In this case it executes 2dd in normal mode

like image 156
FDinoff Avatar answered Oct 05 '22 01:10

FDinoff


Use :g[lobal] with a d[elete] command with a ,+1 range to delete matched line and the next:

:g/word/,+1d 
  • :global
  • :delete
  • command ranges
like image 41
Pavel Anossov Avatar answered Oct 05 '22 03:10

Pavel Anossov