There have been multiple accounts created with the sole purpose of posting advertisement posts or replies containing unsolicited advertising.

Accounts which solely post advertisements, or persistently post them may be terminated.

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.


<span style="color:#323232;">[A,B]
</span><span style="color:#323232;">[A,C]
</span><span style="color:#323232;">[B,C]
</span><span style="color:#323232;">[A]
</span><span style="color:#323232;">[B]
</span>

I can reverse grep for B:


<span style="color:#323232;">> grep --invert-match "B"
</span><span style="color:#323232;">[A,C]
</span><span style="color:#323232;">[A]
</span>

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

Andy , (edited )
@Andy@programming.dev avatar

<span style="color:#323232;">grep -E </span><span style="color:#183691;">'(^[^B]*$|A)'
</span>

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.

TheLugal OP ,
@TheLugal@lemmy.world avatar

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

bizdelnick ,

You don’t need parentheses here.

Andy ,
@Andy@programming.dev avatar

How dare you?

Thanks!

borf ,

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 OP ,
@TheLugal@lemmy.world avatar

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

  • All
  • Subscribed
  • Moderated
  • Favorites
  • random
  • [email protected]
  • lifeLocal
  • goranko
  • All magazines