SaKer
SaKer

Reputation: 107

Delete everything but TWO patterns

Is there a way to delete everything but TWO patterns in bash?

I know i can delete everything but pattern with

sed '/pattern/!d'

but I'm looking for a way delete everything but two patterns... something like this

sed '/pattern1 and pattern2/!d'

I don't know how to do this.

btw. I'm trying to delete everything but <..> and <..>:

Thanks for help.

Upvotes: 1

Views: 134

Answers (4)

Scrutinizer
Scrutinizer

Reputation: 9926

instead of !d you can use -n and the p command:

sed -n '/pattern1/p; /pattern2/p' 

Which should also work with seds other than GNU sed...

Upvotes: 1

jaypal singh
jaypal singh

Reputation: 77105

You can do so with either awk or sed.

$ cat file
foo
bar
baz
qux
$ sed -n '/foo\|bar/p' file
foo
bar
$ awk '/foo|bar/' file
foo
bar

The above will print any lines containing foo or bar. If you wish to be more specific, for instance, only print when foo or bar are at the start of the line, you can use ^, which means print only those that start with your pattern.

Upvotes: 1

omoman
omoman

Reputation: 859

Better answer to what I had before. You could just use grep for this task assuming your patterns are in in.txt and your output will be in out.txt

grep -E -o '(pattern1|pattern2) in.txt > out.txt' 

E is for extended regular expressions and o is to show only matching patterns.

Upvotes: 1

user1907906
user1907906

Reputation:

You want to delete all lines that don't contain pattern1 or pattern2. Use the proper OR for this.

$ cat in.txt
foo
bar
baz
qux
$ sed '/foo\|bar/!d' < in.txt
foo
bar

Upvotes: 1

Related Questions