Tell me more ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question
2  
miv ni g: . – tsilb Aug 31 '09 at 3:46

2 Answers

up vote 11 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

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

Delete lines not containing "foo":

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

It's quite tricky. Read first:

:help /\@!

share|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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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