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

130

39

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

digitaljoel

Posted 2011-03-31T23:00:05.690

Reputation: 1 663

1

Can this question be migrated to http://vi.stackexchange.com/? I tried to flag it for migration but couldn't figure it out.

– Mu Mind – 2015-12-21T16:40:08.590

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 – 2017-10-17T17:14:53.607

Answers

178

You can use

:%g!/price/d

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

Yab

Posted 2011-03-31T23:00:05.690

Reputation: 2 363

2% is optional since the default range is the entire buffer. – stillanoob – 2019-02-06T11:38:47.357

1The percetage sign is redundant. The "g" already selects all lines. A simple :g!/price/d will delete all lines without "price" in them. – Bob60506 – 2019-10-17T06:55:43.013

3I knew it would be easy... – digitaljoel – 2011-03-31T23:28:37.227

36:g! is also known as :v (akin to grep -v). – Chris Johnsen – 2011-04-01T03:17:19.003

3What does the % do? – hippietrail – 2012-10-30T07:05:39.150

4% is a special range in this context that means the whole file. See :help cmdline-ranges. – Heptite – 2012-10-30T18:05:09.777

30

You can also use:

:v/price/d

to delete lines.

MOHRE

Posted 2011-03-31T23:00:05.690

Reputation: 401

1

Fwiw -- Looks like g is for "global" and v for "inverse" (if you believe what you read on vim.famdom).

– ruffin – 2019-04-11T01:08:24.057

help :v in vim confirms it – Paddy3118 – 2019-06-11T09:30:30.360

4

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

Ciro Santilli 新疆改造中心法轮功六四事件

Posted 2011-03-31T23:00:05.690

Reputation: 5 621