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