I know how to do something to every line that matches a pattern, using :g. Is there a way to do something to every line that does not match the pattern?

For example, suppose I want to delete every line that does not match /foo/. I might do something like:

:G/foo/d

(:G is not the opposite of :g, but that is what I am looking for)

Any ideas?

link|improve this question

1  
miv ni g: . – tsilb Aug 31 '09 at 3:46
feedback

2 Answers

up vote 10 down vote accepted

I think there is a inversion within VIM as,

:g!/foo/d

or, like the grep command (below),

:v/foo/d


If you are ready to go to the shell prompt,

grep -v foo filename.txt > new.txt

will do this

link|improve this answer
That did it, thanks! – pkaeding Aug 31 '09 at 3:19
feedback

Delete lines not containing "foo":

:g/^(.+)\@!.foo.$/d

It's quite tricky. Read first:

:help /\@!

link|improve this answer
That is good to know, but I wasn't really looking for a way to invert the regular expression, I was looking for a way to invert the logic that decides if the action needs to be taken. – pkaeding Aug 31 '09 at 14:32
feedback

Your Answer

 
or
required, but never shown

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