202

In vim I can delete all lines that contain the word "price" with this

:g /price/d

How can I delete all lines that do NOT contain the word "price"?

2
  • 2
    Can this question be migrated to vi.stackexchange.com? I tried to flag it for migration but couldn't figure it out.
    – Mu Mind
    Dec 21, 2015 at 16:40
  • 1
    @MuMind It's on topic here, so no need to migrate. "Don't migrate for the sake of migration. We only migrate questions because they are off-topic on the original site. It is perfectly possible for a question to be on-topic on multiple sites, but that is not a reason to migrate it elsewhere, unless the OP requests migration." Also, only SE employees can migrate after 60 days and it's very rare that they will (not even moderators can migrate an old question).
    – 8bittree
    Oct 17, 2017 at 17:14

3 Answers 3

272

You can use

:g!/price/d

to delete every line that doesn't contain "price"

As answered below, g! is an alias to v. this is equivalent to

:v/price/d

6
  • 3
    I knew it would be easy... Mar 31, 2011 at 23:28
  • 50
    :g! is also known as :v (akin to grep -v). Apr 1, 2011 at 3:17
  • 3
    What does the % do? Oct 30, 2012 at 7:05
  • 4
    % is a special range in this context that means the whole file. See :help cmdline-ranges.
    – Heptite
    Oct 30, 2012 at 18:05
  • 2
    % is optional since the default range is the entire buffer.
    – stillanoob
    Feb 6, 2019 at 11:38
44

You can also use:

:v/price/d

to delete lines.

2
11
%!grep "price"

is another option that can be considerably faster than :v for large files.

Tested on Vim 7.4, Ubuntu 14.04, 1M line log file.

Lines that contain word: https://stackoverflow.com/questions/1725265/how-can-i-delete-all-lines-that-do-not-begin-with-certain-characters/42714334#42714334

1
  • 1
    Super fast and a marvelous solution
    – zardilior
    Feb 20 at 19:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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