tags:

views:

925

answers:

6

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...

+10  A: 

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

:g!/ERROR/d
too much php
`:v/ERROR/d` is equivalent
rampion
A: 

If you're on a Unix machine (sounds like you are) you could just use grep -v ERROR yourfilename > newfile.

Paul J
A: 

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

Jaelebi
That's true, but such a regex will match every *character* that's not E, which is different from matching all *lines* that do not contain E. Also, such a negative match is awkward to extend beyond one character.
Greg Hewgill
A: 

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
ghostdog74
+4  A: 

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).

Greg Hewgill
+1 for a command that doesn't require leaving vim / redirecting into a different file
too much php
Maybe not the best of examples, as `:grep` and `:sort` do have built-in meanings in Vim (which are different than `:!grep` and `:!sort`, just to be confusing).
ephemient
A: 

Using a negative lookahead worked.

Thr4wn