32

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

5 Answers 5

55

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

:g!/ERROR/d
Sign up to request clarification or add additional context in comments.

1 Comment

:v/ERROR/d is equivalent
8

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

2 Comments

+1 for a command that doesn't require leaving vim / redirecting into a different file
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).
1

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

Comments

1

Using a negative lookahead worked.

2 Comments

Not a very useful answer without an example: :%s/^\(\ERROR\)\@!$\n//g. In Vim the \@! is the negative lookahead indicator, not the (?!) format from that link. The :g! answer is easier though.
I agree with @atomicules, but I'm nevertheless upvoting Alexander's answer because 'negative lookahead' is a useful term for further websearching.
0

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.