CFR
CFR

Reputation: 131

Sed and delete lines matching "String1 AND string 2"

I can't find how to make that, I want to remove every line containing ACE and REE. only if both words are present.

sed -i '/ACE/d' $1

Upvotes: 0

Views: 2037

Answers (3)

UlfR
UlfR

Reputation: 4395

If you need to match both words but you don't know the order you need to try both cases like so:

sed -i '/\(ABC.*DEF\)\|\(DEF.*ABC\)/d' FileName

It will match any row with either ABC.*DEF or DEF.*ABC and then remove it.

NOTE: With the pattern similar to the following you will also match the case where ABC occurs 2 times and DEF 0 times, and that is not what you want.

sed -i '/\(ABC\|DEF\).*\(ABC\|DEF\)/d' FileName

Upvotes: 1

Kalanidhi
Kalanidhi

Reputation: 5092

Try this method

sed -i '/ACE.*RRE/d' FileName

Or

sed -i '/\(ACE\|CH3\).*\(CH3\|ACE\)/d' FileName

Example:

cat sample

Output:

336 ACE CH3 1.00
123 ACE 321 test
This ACE for testing CH3

Command:

sed  '/ACE.*CH3/d' sample

Output:

123 ACE 321 test

Upvotes: 1

Tom Fenech
Tom Fenech

Reputation: 74645

I would suggest using awk, which would allow you to specify both patterns separately:

awk '!(/ACE/ && /REE/)' file

All lines are printed, except for those where both patterns match.

The advantage of this approach is that it would work regardless of the order in which the two strings appear.

To achieve an "in-place" edit, you can go for the standard approach:

awk '!(/ACE/ && /REE/)' file > tmp && mv tmp file

i.e. output to a temporary file and then overwrite the source.

Upvotes: 2

Related Questions