Find first non-matching line in VIM

13,219

Solution 1

you can use negative look-behind operator @<!

e.g. to find all lines not containing "a", use /\v^.+(^.*a.*$)@<!$

(\v just causes some operators like ( and @<! not to must have been backslash escaped)

the simpler method is to delete all lines matching or not matching the pattern (:g/PATTERN/d or :g!/PATTERN/d respectively)

Solution 2

I believe if you simply want to have your cursor end up at the first non-matching line you can use visual as the command in your global command. So:

:v/pattern/visual

will leave your cursor at the first non-matching line. Or:

:g/pattern/visual

will leave your cursor at the first matching line.

Solution 3

I'm often in your case, so to "clean" the logs files I use :

:g/all is ok/d

Your grep -v can be achieved with

:v/error/d

Which will remove all lines which does not contain error.

Solution 4

It's probably already too late, but I think that this should be said somewhere.

Vim (since version about 7.4) comes with a plugin called LogiPat, which makes searching for lines which don't contain some string really easy. So using this plugin finding the lines not containing all is ok is done like this:

:LogiPat !"all is ok"

And then you can jump between the matching (or in this case not matching) lines with n and N.

You can also use logical operations like & and | to join different strings in one pattern:

:LP !("foo"|"bar")&"baz"

LP is shorthand for LogiPat, and this command will search for lines that contain the word baz and don't contain neither foo nor bar.

Solution 5

I just managed a somewhat klutzy procedure using the "g" command:

:%g!/search/p

This says to print out the non-matching lines... not sure if that worked, but it did end up with the cursor positioned on the first non-matching line.

(substitute some other string for "search", of course)

Share:
13,219
Dummy00001
Author by

Dummy00001

Жыве Беларусь!

Updated on July 17, 2022

Comments

  • Dummy00001
    Dummy00001 almost 2 years

    It happens sometimes that I have to look into various log and trace files on Windows and generally I use for the purpose VIM.

    My problem though is that I still can't find any analog of grep -v inside of VIM: find in the buffer a line not matching given regular expression. E.g. log file is filled with lines which somewhere in a middle contain phrase all is ok and I need to find first line which doesn't contain all is ok.

    I can write a custom function for that, yet at the moment that seems to be an overkill and likely to be slower than a native solution.

    Is there any easy way to do it in VIM?