How to delete all lines that do NOT contain a certain word in Vim?

94,501

Solution 1

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

Solution 2

You can also use:

:v/price/d

to delete lines.

Solution 3

%!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

Share:
94,501

Related videos on Youtube

digitaljoel
Author by

digitaljoel

Professional Java programmer since 2000 working with Spring, JPA, hibernate, maven, and other related technologies. Also an AKKI Kenpo black belt.

Updated on September 18, 2022

Comments

  • digitaljoel
    digitaljoel over 1 year

    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"?

    • Mu Mind
      Mu Mind over 8 years
      Can this question be migrated to vi.stackexchange.com? I tried to flag it for migration but couldn't figure it out.
    • 8bittree
      8bittree over 6 years
      @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).
  • digitaljoel
    digitaljoel about 13 years
    I knew it would be easy...
  • Chris Johnsen
    Chris Johnsen about 13 years
    :g! is also known as :v (akin to grep -v).
  • hippietrail
    hippietrail over 11 years
    What does the % do?
  • Heptite
    Heptite over 11 years
    % is a special range in this context that means the whole file. See :help cmdline-ranges.
  • stillanoob
    stillanoob about 5 years
    % is optional since the default range is the entire buffer.
  • vjalle
    vjalle about 5 years
    Fwiw -- Looks like g is for "global" and v for "inverse" (if you believe what you read on vim.famdom).
  • Paddy3118
    Paddy3118 almost 5 years
    help :v in vim confirms it
  • Bob60506
    Bob60506 over 4 years
    The percetage sign is redundant. The "g" already selects all lines. A simple :g!/price/d will delete all lines without "price" in them.
  • zardilior
    zardilior about 2 years
    Super fast and a marvelous solution