Inverting match with grep, unless another term exists

I have a list containing a set of tags, and would like to exclude one tag, unless another tag exists in the line.

Say I have the following list, and want to exclude B, unless A is present.

[A,B]
[A,C]
[B,C]
[A]
[B]

I can reverse grep for B:

> grep --invert-match "B"
[A,C]
[A]

How can I find the previous list, but also the item containing [A,B]?

16 points · 6 comments · view on lemmy.world

6 Comments

borf@lemmynsfw.com · 7 pts · 2y (1 reply)

I like to use awk instead of grep wherever possible, especially for weird logic like this.

awk '!/B/ || /A.*B/' is one way to skin that cat. If you don't care what order A and B are in on the lines containing both, then awk '!/B/ || (/A/ && /B/)' will work.

TheLugal@lemmy.world · 1 pts · 2y

Thank you! This was exactly was I was looking for. :)

Andy@programming.dev · 7 pts · 2y (3 replies)
grep -E '(^[^B]*$|A)'

EDIT: Whoops, I meant to make this a top-level comment.

EDIT 2: On one client it looked like a nested comment and on this other client it looks top level and now I'm a confused old man.

bizdelnick@lemmy.ml · 1 pts · 2y (1 reply)

You don't need parentheses here.

Andy@programming.dev · 1 pts · 2y

How dare you?

Thanks!

TheLugal@lemmy.world · 1 pts · 2y

Haha, on Lemmy.World it looks like a top level. Thank you, either way :)