how to do a vim search inverse search for all lines with out text

18

6

with grep I can do a grep -v "my search" to get all the lines with out "my search"

with sed I can sed '/baz/!s/foo/bar/g' to find replace text on lines with out baz

Is there a way to do the same thing vim. And is it possible but with out the "s///" syntax. Using just the "/" search syntax.

nelaaro

Posted 2012-01-30T11:56:47.880

Reputation: 9 321

Answers

29

:g/pattern/

matches all the lines were pattern is found.

:v/pattern/

does the opposite. See :h global for more details.

You can use it like this:

:v/pattern/norm Ipattern not found - <CR>

to prepend "pattern not found - " to every line that doesn't have "pattern" or

:v/pattern/s/nrettap/pattern

to replace "nrettap" with "pattern" on every line that doesn't have "pattern".

Contrived examples, yes.

romainl

Posted 2012-01-30T11:56:47.880

Reputation: 19 227

I lol'd on "nrettap". – UncleZeiv – 2012-01-30T14:44:14.113

6

To search for the lines not containing foo, for example, do:

/^\(\(.*foo.*\)\@!.\)*$

Source: http://vim.wikia.com/wiki/Search_for_lines_not_containing_pattern_and_other_helpful_searches

Karolos

Posted 2012-01-30T11:56:47.880

Reputation: 2 304

1I did not know about the @ directive that lets you reference the previous atom in search. Very useful. – nelaaro – 2012-01-30T14:19:59.260

Even if correct, this is really costly. – Benoit – 2012-01-30T17:25:57.427

1

Using the :v commandEdit The traditional approach to find lines not matching a pattern is using the :v command:

:v/Warning/p

A neat trick when working with a large log file where you want to filter out as many irrelevant lines as possible before you get started on your real search is to save the file under a temporary name and delete all non-matching lines there:

:sav junk.log
:v/warning/d

You are now are editing a clone of your original file with all lines not matching "warning" removed and you can edit it at will.

Ref: https://vim.fandom.com/wiki/Search_for_lines_not_containing_pattern_and_other_helpful_searches

selfboot

Posted 2012-01-30T11:56:47.880

Reputation: 111