Guuk
Guuk

Reputation: 609

Delete lines that contain two strings

I am trying to delete some lines in a text file using sed. I only want to delete lines that contains two strings. The command \| is equivalent to the boolean OR. What is the command for the boolean operator AND?

I am looking for something like this:

sed '/strA'AND'strB/d' file.txt

Upvotes: 0

Views: 2481

Answers (4)

potong
potong

Reputation: 58440

This might work for you (GNU sed):

sed '/strA/!b;/strB/d' file

If the line does not contain strA bail out. If it does and it also contains strB delete it.

Upvotes: 1

PatJ
PatJ

Reputation: 6144

You cannot put two selectors on one command, but you can put a command between braces and do that:

sed '/strA/{/strB/d}' file.txt

The bad part in that is, if you have a lot of string you want to test, you may have a lot of {} to handle. Also, it is probably not very efficient.

Upvotes: 1

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed '/strA/{
        /strB/ d
        }' YourFile
  • AND is a sub filter ( if filter strA, then filter on strB on same content)
  • order is no important itself for the filtering but could change the performance depending occurence of each pattern)

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174716

You could use the same \| OR (alternation) operator. The below sed command would delete all the lines which has both strA and strB , irrespective of the order.

sed '/strA.*strB\|strB.*strA/d' file.txt

If you want to delete the lines in which strA always comes before strB then you could use this.

sed '/strA.*strB/d' file.txt

Upvotes: 2

Related Questions