Skip to content
Home » Linux » How to grep A But Not B out of Text

How to grep A But Not B out of Text

3 kinds of exquisite fruit platters that customers can order in our restaurant.
[root@localhost ~]# cat -n fruits.lst
     1  apple banana cherry mango
     2  watermelon banana kiwi pineapple
     3  orange guava mango banana apple

All we have known is that Mr. Thompson likes banana, but NOT mango, what should we recommend? Let's see what platters have banana.
[root@localhost ~]# cat -n fruits.lst | grep banana
     1  apple banana cherry mango
     2  watermelon banana kiwi pineapple
     3  orange guava mango banana apple

All platters have banana, we should add a dislike-filter to the result:
[root@localhost ~]# cat -n fruits.lst | grep banana | grep -v mango
     2  watermelon banana kiwi pineapple

Now we know we should recommend Platter #2 for Mr. Thompson to order.

As you can see, we arrange filters in a sequential chain to narrow down the result.

Leave a Reply

Your email address will not be published. Required fields are marked *