0

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
Guuk
  • 505
  • 3
  • 17
  • possible duplicate of [Regular Expressions: Is there an AND operator?](http://stackoverflow.com/questions/469913/regular-expressions-is-there-an-and-operator) – tripleee Feb 17 '15 at 12:38
  • @tripleee not a duplicate, sed use a sub part of RegEx implementation – NeronLeVelu Feb 17 '15 at 12:41
  • @NeronLeVelu The marked duplicate is general enough to provide solutions for most regex dialects, though conspicuously not specifically for `sed`. If you can find a better duplicate, please link to it -- this is a frequent enough question that I'm sure you can find one. – tripleee Feb 17 '15 at 12:44

4 Answers4

3
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)
NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43
2

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
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • This becomes quite heavy when you want the AND of a lot of strings. – PatJ Feb 17 '15 at 12:46
  • Also, `/abc.*cba/` doesn't match `abcba` even though it should (maybe not in the case of the asker). – PatJ Feb 17 '15 at 12:49
1

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.

PatJ
  • 5,996
  • 1
  • 31
  • 37
1

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.

potong
  • 55,640
  • 6
  • 51
  • 83