Rahul
Rahul

Reputation: 1005

grep parts of string with match and not match?

I have a log file which contains string errorCode:null or errorCode:404 etc. I want to find all occurrences where errorCode is not null.

I use:

grep -i "errorcode" -A 10 -B 10  app.2020-.* | grep -v -i "errorCode:null"`, 

grep -v -i 'errorcode:[0-9]^4' -A 10 -B 10  app.2020-.* 

but this is not the right regex match. How could this be done?

Upvotes: 1

Views: 52

Answers (2)

Dominique
Dominique

Reputation: 17565

I have no idea why you are using -A 10 -B 10, I've just used the following command and everything is working fine:

grep -i "ErrorCode" test.txt | grep -v -i "Errorcode:null"

This the file content:

Errorcode:null
Errorcode:405
Errorcode:504
Nonsens

This is the output of the command:

Errorcode:405
Errorcode:504

Upvotes: 1

anubhava
anubhava

Reputation: 785991

If you have gnu-grep then use a negative lookahead in regex as this with -P option:

grep -Pi 'errorcode(?!:null)' -A 10 -B 10 app.2020-.*

If you don't have gnu grep then try this awk:

awk '/errorcode/ && !/errorcode:null/' app.2020-.*

it would require more bit of code in awk to match equivalent of -A 10 -B 10 options of grep.

Upvotes: 1

Related Questions