Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim search for a pattern and if NOT occurs delete line

Tags:

vim

filter

I've read this question, but I want to know how can I delete the line when the pattern DOESN'T occur.

like image 435
Lucas Gabriel Sánchez Avatar asked Oct 28 '09 17:10

Lucas Gabriel Sánchez


People also ask

How do you delete certain lines in vi?

To delete a line in Vi or Vim, switch to normal mode first. If you're into command mode or insert mode, you can switch back to normal mode by pressing Escape. Highlight the line that you want to delete, then hit dd or D on the keyboard.

How do I match a pattern in Vim?

In normal mode, press / to start a search, then type the pattern ( \<i\> ), then press Enter. If you have an example of the word you want to find on screen, you do not need to enter a search pattern. Simply move the cursor anywhere within the word, then press * to search for the next occurrence of that whole word.


3 Answers

Deleting the rest of the line when a pattern does not occur is ... hard for me to understand.

Did you mean, delete the whole line if it doesn't have a pattern?

:v/pattern/d

If you meant, preserve the line but clobber the characters:

:v/pattern/s/.*//
like image 57
DigitalRoss Avatar answered Oct 19 '22 16:10

DigitalRoss


Equivalently:

:g!/pattern/d

Easier to remember in my opinion, because! is ingrained as "not" in my brain.

like image 38
Brian Carper Avatar answered Oct 19 '22 16:10

Brian Carper


:v/pattern/s/.*//
like image 39
chaos Avatar answered Oct 19 '22 14:10

chaos