Alexander Bird
Alexander Bird

Reputation: 40639

regex with negative matching (ie, find string that _doesn't_ match regex)

I have a log file with the string "ERROR" on some lines. I want to delete every line that doesn't have ERROR so that I can see just what needs fixing. I was going to do something like the following in vim:

%s/!(ERROR)//

to replace non-error lines with an empty string.

I do not believe that standard regexes can do this, but maybe I'm wrong...

Upvotes: 32

Views: 19913

Answers (5)

Alexander Bird
Alexander Bird

Reputation: 40639

Using a negative lookahead worked.

Upvotes: 1

Greg Hewgill
Greg Hewgill

Reputation: 993125

In vim, you can run any filter command on the text in the buffer. For example,

:%!grep ERROR

will replace the entire buffer with only the lines that match the given regular expression.

This is useful for more than just grep, for example you can sort the lines in the buffer with :%!sort. Or, you can do the same for any range of text using the V command to mark the block and then :!filter-command (vim will automatically fill in '<,'> for you to indicate the currently marked block).

Upvotes: 8

ghostdog74
ghostdog74

Reputation: 342373

if on *nix, you can use grep -v or awk

awk '!/ERROR/' file | more 

on a windows machine, you can use findstr

findstr /v /c:ERROR file | more

Upvotes: 1

Jaelebi
Jaelebi

Reputation: 6119

A negative matching regex will use ^ For eg. [^E] will match everything except E.

Upvotes: 0

too much php
too much php

Reputation: 91028

Use the :g! command to delete every line that doesn't match.

:g!/ERROR/d

Upvotes: 55

Related Questions