felixbade
felixbade

Reputation: 1087

Grep exclude line only if multiple patterns match

I want to find lines that do not contain both "path": "/" and "User-Agent": "curl. Lines that contain only one of those should be included.

In other words, how can I exclude a line only if it matches multiple patterns?

Upvotes: 0

Views: 711

Answers (3)

anubhava
anubhava

Reputation: 784888

This awk should do the job:

awk '(/"path": "\/"/ && !/"User-Agent": "curl/) || 
     (!/"path": "\/"/ && /"User-Agent": "curl/)
     {print FILENAME ":" $0}' *

This goes by this approach:

awk '(/match1/ && !/match2/) || (!/match1/ && /match2/)' *

so in other words print if any of the 2 words match but not when both match.

Upvotes: 0

fedorqui
fedorqui

Reputation: 289495

These double checks in the same line are better done with awk:

awk '! (/"path": "\/"/ && /"User-Agent": "curl/)' file

This uses the logic awk '! (condition1 && condition2)', so it will just fail whenever both strings are found.

Test

$ cat a
"path": "/" and "User-Agent": "curl
"path": "/" hello
bye "User-Agent": "curl
this is a test
$ awk '! (/"path": "\/"/ && /"User-Agent": "curl/)' a
"path": "/" hello
bye "User-Agent": "curl
this is a test

Upvotes: 3

Damian Nikodem
Damian Nikodem

Reputation: 1289

you can use | in a grep command to signal "or", and you can use the -v argument to

so:

grep -v \"path\"\:\ \"/\"\\\|curl

would print every line that does not include "path": "/" or curl.

Upvotes: 0

Related Questions