Chris
Chris

Reputation: 1219

How to delete line that doesn't contain pattern 1 or pattern 2

Using sed I can do this

sed -i '' '/myPattern/!d' file

But how can I make it compare against 2 patterns? So it only deletes lines that do not have at least 1 of the 2 patters?

Upvotes: 1

Views: 791

Answers (4)

albertodegama2
albertodegama2

Reputation: 11

You can use:

Delete any line not containing alpha or beta or gama.

sed -n '/alpha\|beta\|gama/p' < 1.txt > 2.txt

Upvotes: 1

Mark Setchell
Mark Setchell

Reputation: 207465

I think I'd go with a case-insensitive (-i) negative (-v) grep for an extended (-E) alternation (|) of two patterns:

grep -viE `pattern1|pattern2' someFile

Upvotes: 0

Thor
Thor

Reputation: 47099

This sounds like a job for grep, e.g.:

seq 10 | grep -e 3 -e 7

Output:

3
7

Upvotes: 1

hek2mgl
hek2mgl

Reputation: 157992

You may use multiple commands with -e and use -n and p instead of !d:

sed -n -i '' -e '/myPattern/p' -e '/myPattern2/p' file

Usually I prefer awk for that task since you can use boolean logic, like:

awk '/pattern1/ || /pattern2/' file

or

awk '/pattern1/ && /pattern2/' file

and so on.


Btw, having GNU awk you can also edit files in place:

gawk -i inplace '/pattern1/||/pattern2/' file

Upvotes: 0

Related Questions